I have some problems with hibernate validations with Spring. I did everything as explained in an online tutorial, but it’s not working and I just go to the next page without validation error.
import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Customer { private String firstName; @NotNull() @Size(min=1, message = "this field must not to be empty") private String lastName;
Controller:
@RequestMapping("/processForm") public String processForm(@ModelAttribute("customer") @Valid Customer customer, BindingResult bindingResult) { if(bindingResult.hasErrors()) { return "customer-form"; } return "customer-confirmation"; }
customer-form.jsp
<form:form action="processForm.form" modelAttribute="customer"> First name: <form:input path="firstName"/> <br> Last name (*): <form:input path="lastName"/> <form:errors path="lastName" cssClass="error"/> <input type="submit" value="Submit"/> </form:form>
So, there are no errors in BindingResult when I have an empty field for lastName. What am i doing wrong?
Advertisement
Answer
Add hibernate-validator
in your classpath if it does not exist already. If you are using any build tool like gradle
or maven
just add hibernate-validator
to dependencies.
For example:
Gradle:
compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.13.Final'
Maven:
<dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency>