What configuration is needed to use annotations from javax.validation.constraints
like @Size
, @NotNull
, etc.? Here\'s my code:
I come here some years after, and I could fix it thanks to atrain's comment above. In my case, I was missing @Valid
in the API that receives the Object (a POJO in my case) that was annotated with @Size
. It solved the issue.
I did not need to add any extra annotation, such as @Valid
or @NotBlank
to the variable annotated with @Size
, just that constraint in the variable and what I mentioned in the API...
Pojo Class:
...
@Size(min = MIN_LENGTH, max = MAX_LENGTH);
private String exampleVar;
...
API Class:
...
public void exampleApiCall(@RequestBody @Valid PojoObject pojoObject){
...
}
Thanks and cheers
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.
for method parameters you can use Objects.requireNonNull() like this:
test(String str) {
Objects.requireNonNull(str);
}
But this is only checked at runtime and throws an NPE if null. It is like a preconditions check. But that might be what you are looking for.
I came across this problem recently in a very similar situation: Met all requirements as the top-rated answer listed but still got the wrong result.
So I looked at my dependencies and found I was missing some of them. I corrected it by adding the missing dependencies.
I was using hibernate, the required dependencies were:
*Snapshot taken in class "Spring & Hibernate for Beginners" @ Udemy
In my case i removed these lines
1-import javax.validation.constraints.NotNull;
2-import javax.validation.constraints.Size;
3- @NotNull
4- @Size(max = 3)
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