I have a entity called User and I want to validate a mobile number field
The mobile number field is not mandatory it can be left blank but it should be a 10 digit number.
If the user enters any value less then 10 digits in length then an error should be thrown.
Below is my User class.
public class User {
@Size(min=0,max=10)
private String mobileNo;
}
When I used @Sized annotation as mentioned above, I could validate values that were greater than 10 but if the user entered less than 10 digits no error was raised.
My requirement is, if user left the mobileNo field blank that is valid but if a value is entered then the validation should ensure that the number entered is 10 digits and 10 digits only.
Which annotation I should use for this requirement?
@Size(min=10,max=10)
would do the job if by blank you mean null.
If you don't put @NotNull
annotation, null
value would pass validation.
If your blank means empty String then you need to use @Pattern
validator:
@Pattern(regexp="(^$|[0-9]{10})")
this matches either empty string or 10 digits number.