Search code examples
javaspringspring-bootspring-mvcthymeleaf

Spring Boot CRUD Application with Thymeleaf - BindingResult result


I have a SpringBoot app with this bean:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(NON_NULL)
public class UserPayload implements Serializable {

    private Long id;
    @NotEmpty
    private String password;
    @NotEmpty
    private String confirmPassword;
    @NotBlank(message = "Name is mandatory")
    @NotEmpty
    @NotNull
    private String name;
...
}

and the controller:

@PostMapping("/adduser.html")
    public String addUser(@Valid UserPayload userPayload,
                            BindingResult result,
                            Model model,
                            @RequestParam("files") MultipartFile[] multipartFiles) {
...
}

on the template:

<form action="#" th:action="@{/adduser.html}" th:object="${user}" method="post" enctype="multipart/form-data">


     <input type="text" id="name" class="form-control" th:field="*{name}"  placeholder="Introduce you name">

...

</form>

but BindingResult result shows 0 errors when all the fields are empty


Solution

  • Your problem could be motivated for different reasons.

    One thing you can try is to annotate the UserPayload object with a ModelAttribute annotation:

    @PostMapping("/adduser.html")
    public String addUser(@ModelAttribute("userPayload") @Valid UserPayload userPayload,
                          BindingResult result,
                          Model model,
                          @RequestParam("files") MultipartFile[] multipartFiles) {
    ...
    }
    

    Perhaps it could be of help as it seems you are also providing the files parameter. Please, adjust the model attribute name as appropriate.

    Please, also verify that you have an implementation of the Validation API in your maven dependencies, not only the java.validation API, like hibernate-validator:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.3.Final</version>
    </dependency>
    

    Please, set the right version according with the rest of libraries in your project: if you are using Spring dependency management you can safely rely on it.