Annotations from javax.validation.constraints not working
Solution 1:
For JSR-303 bean validation to work in Spring, you need several things:
- MVC namespace configuration for annotations:
<mvc:annotation-driven />
- The JSR-303 spec JAR:
validation-api-1.0.0.GA.jar
(looks like you already have that) - An implementation of the spec, such as Hibernate Validation, which appears to be the most commonly used example:
hibernate-validator-4.1.0.Final.jar
- In the bean to be validated, validation annotations, either from the spec JAR or from the implementation JAR (which you have already done)
- In the handler you want to validate, annotate the object you want to validate with
@Valid
, and then include aBindingResult
in the method signature to capture errors.
Example:
@RequestMapping("handler.do")
public String myHandler(@Valid @ModelAttribute("form") SomeFormBean myForm, BindingResult result, Model model) {
if(result.hasErrors()) {
...your error handling...
} else {
...your non-error handling....
}
}
Solution 2:
You should use Validator to check whether you class is valid.
Person person = ....;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<Person>> violations = validator.validate(person);
Then, iterating violations set, you can find violations.
Solution 3:
In my case, I was using spring boot version 2.3.0. When I changed my maven dependency to use 2.1.3 it worked.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
</dependencies>
Solution 4:
You would have to call a Validator on the Entity if you want to validate it. Then you will get a set of ConstraintViolationException, which basically show for which field/s of your Entity there is a constraint violation and what exactly was it. Maybe you can also share some of the code you expect to validate your entity.
An often used technique is to do validation in @PrePersist and rollback transaction if using multiple data modifications during transaction or do other actions when you get a validation exception.
Your code should go like this:
@PrePersist
public void prePersist(SomeEntity someEntity){
Validator validator = Validation.buildDefaultValidatorFactory.getValidator();
Set<ConstraintViolation<SomeEntity>> = validator.validate(someEntity);
//do stuff with them, like notify client what was the wrong field, log them, or, if empty, be happy
}
Solution 5:
You can also simply use @NonNull
with the lombok library instead, at least for the @NotNull
scenario. More details: https://projectlombok.org/api/lombok/NonNull.html