Spring Boot + Thymeleaf form validation error not displaying
Check these by these steps.
Make sure BindingResult
just follows up with the object variable
@PostMapping("/save")
public String save(@Valid Product product,
BindingResult bindingResult,
RedirectAttributes attributes) {
// th:object = "${product}"
}
Here, it follows up producrt
object.
use @ModelAttribute
If object variable name do not same as it’s camel style of java class name, use @ModelAttribute
public String save(@Valid @ModelAttribute("category") ProductCategory category,
BindingResult bindingResult,
RedirectAttributes attributes) {
// th:object = "${category}"
}
Here, the camel style of ProductCategory
is productCategory
, but we named the variable name is category
. We must use @ModelAttribute("category")
to make sure Model
can find it correctly.
Do not redirect
if valid failed.
If the validation failed, it should render back to the original template. If you redirect it to new page, the errors
won’t be saved.
return "redirect:/edit";
to
return "edit"
Reference: