Validating RequestParam with multiple annotations

58 Views Asked by At

I have only one request param in the rest controller in spring boot 3. I have added @NotBlank and @Size annotations for the validation of that one request param. While validation both annotations are validate and provide exception with both message randomly.

@RestController
@Validated
public class Controller {

  @PostMapping(LinkConfig.AUTH_REGISTER_URL)
  public ResponseEntity<?> post(@RequestParam
                                      @NotBlank(message = "Invalid Firstname: Firstname is empty.")
                                      @NotNull(message = "Invalid Firstname: Firstname is NULL.")
                                      @Size(min = 3, max = 20, message = "Invalid Firstname: Firstname must be of 3 - 30 characters.") String firstname) {
  }           
}

This will give this type of message from the ConstraintViolationException

{
    "status": false,
    "message": [
        "registerUser.firstname: Invalid Firstname: Firstname must be of 3 - 30 characters., registerUser.firstname: Invalid Firstname: Firstname is empty."
    ]
}

But I want to validate those annotations serially i.e. @NotBlank first then @Size second after validation @NotBlank.

{
    "status": false,
    "message": [
        "registerUser.firstname: Invalid Firstname: Firstname is empty."
    ]
}

Then,

{
    "status": false,
    "message": [
        "registerUser.firstname: Invalid Firstname: Firstname must be of 3 - 30 characters."
    ]
}

I don't want to use custom class validation and grouping. Then, How can I achieve this type of validation? Please help me with this.

0

There are 0 best solutions below