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.
For those who are looking for a custom validator for phone numbers using libphonenumber
PhoneNumber.java libphonenumber requires locale for validation so we need to create a custom class for storing phone and regioncode
public class PhoneNumber {
@NotEmpty
private String value;
@NotEmpty
private String locale;
}
@Phone Annotation Will be used to annotate fields for validation
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = PhoneNumberValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String locale() default "";
String message() default "Invalid phone number";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
PhoneNumberValidator.java It will check phone's validity for the provided region code
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PhoneNumberValidator implements ConstraintValidator<Phone, PhoneNumber> {
@Override
public void initialize(Phone constraintAnnotation) {
}
@Override
public boolean isValid(PhoneNumber phoneNumber, ConstraintValidatorContext context) {
if(phoneNumber.getLocale()==null || phoneNumber.getValue()==null){
return false;
}
try{
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
return phoneNumberUtil.isValidNumber(phoneNumberUtil.parse(phoneNumber.getValue(), phoneNumber.getLocale()));
}
catch (NumberParseException e){
return false;
}
}
}
Usage
@Phone
private PhoneNumber phone;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With