Annotations from javax.validation.constraints not working

后端 未结 15 1278
广开言路
广开言路 2020-11-28 06:23

What configuration is needed to use annotations from javax.validation.constraints like @Size, @NotNull, etc.? Here\'s my code:

相关标签:
15条回答
  • 2020-11-28 06:35

    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

    0 讨论(0)
  • 2020-11-28 06:37

    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.

    0 讨论(0)
  • 2020-11-28 06:38

    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.

    0 讨论(0)
  • 2020-11-28 06:38

    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

    0 讨论(0)
  • 2020-11-28 06:40

    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)

    0 讨论(0)
  • 2020-11-28 06:49

    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

    0 讨论(0)
提交回复
热议问题