Spring Boot + Thymeleaf form validation error not displaying

12 Uncategorized Leave a Comment

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:

  1. BindingResult never makes it into the template so that errors cannot be displayed
  2. Problem with bindingResult.hasErrors() in Spring Boot with Thymeleaf.
  3. Thymeleaf error not displayed Spring 4.x

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *