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;