0

Tried to add @Max validation for the sizes request parameter. However, it seems whatever value I put in will be valid.

A simple controller method in a spring boot application.

    @GetMapping("/all")
public String getAll(@RequestParam @Max(value=20, message = "should be less than 20") int sizes) {
    if (sizes > 20) {
        return "Pass but not valid";
    }
    return "Valid";
}

when request param sizes is 21, I get Pass but not valid rather error message http://localhost:8080/all?sizes=21

Any advice? Thanks

user1619397
  • 680
  • 2
  • 11
  • 23

2 Answers2

2

dit you put @Validated above you class?

Willem
  • 992
  • 6
  • 13
0

I found the following answer (Spring Controller: RequestParam not validated despite @Valid and @Size) helpful for exactly this question.

Basically, it says that:

  1. MethodValidationPostProcessor needs to be added to a configuration.
  2. @Validated annotation needs to be added on top of the controller class.
  3. Possibly some exceptions like ConstraintViolationException or MethodArgumentNotValidException will need to be handled if customized responses are wanted.

For this setup to run, I had to add spring-boot-starter-validation like it's said in this answer: "The Bean Validation API is on the classpath but no implementation could be found" preventing startup

lisymcaydnlb
  • 150
  • 2
  • 12