5

i'm trying to do a validation of only positive numbers inside the request in spring boot

Public ResponseEntity getId(@RequestParam(value =“idPer”)@Pattern(regexp=“^[0-9]*$”),message = “the value is negative”)
@NotNull(message = “the value is empty ”) Long idPer){
}

in my exceptionhandler I get this exception

no validator could be found for constraint 'javax.validation.constraints.pattern' validatingtype long

I have the @validated above my controller class

what am I doing wrong?

1
  • 1
    You can also use the Min() constraint rather than relying on regex. Commented Sep 9, 2020 at 18:08

1 Answer 1

5

Check documentation of @Pattern. It is applicable to CharSequence i.e. String bur not allowed for Long which is what you are using in your method.

You may refactor your code like this:

public ResponseEntity getId (
        @Pattern(regexp="^[0-9]+$", message="the value must be positive integer")
        @RequestParam("idPer") final String idPerStr) {

    Long idPer = Long.valueOf(idPerStr);
    // rest of your handler here
}

Also note that @NotNull is not required because we are using + quantifiers that allows only 1 or more digits in pattern.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.