I'm working with spring boot, one of the inputs of my object, has to accept only a set of integers, and I'm not getting it.
This is my last approach:
@Pattern(regexp="\\d{1111}|\\d{2222}|\\d{3333}|\\d{4444}", message="The value has to be '1111','2222','3333' or '4444'")
private int code;
This is not valid because I'm getting this error:
"statusText": "HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Integer'. Check configuration for 'code'",
How can I manage this?
CodePudding user response:
The problem is that @Pattern only works on strings.
You could use a @Digits validator to validate how many digits you must have in the integer part: https://www.baeldung.com/javax-bigdecimal-validation#3-digits
If this doesn't work for you, then you will have to write your own custom validator: https://www.baeldung.com/spring-mvc-custom-validator#custom-validation
CodePudding user response:
@Pattern Annotation works only with strings and not integers. You could migrate your int to a String if that is suitable. Then it would work.
You could also implement your own Validator as seen here.
CodePudding user response:
As others have already answered @Pattern does not work with integers, but with strings(CharSequence to be more precise). But i want to note that your regex pattern does not match the error message.
The pattern you specified means - match a number with a length of 1111 digits, or length of 2222 digits, and so on.
According to the message you need pattern like ^1111$|^2222$|^3333$|^4444$ or ^([1234])\1{3}$, which means match 1111, or 2222, or 3333, or 4444 exactly.
CodePudding user response:
One the solution can be
@Pattern(regex = "[0-9] ")
private Integer code;
