对于那些正在寻找使用libphonenumber的电话号码的自定义验证器的人
PhoneNumber.java libphonenumber 需要语言环境进行验证,因此我们需要创建一个自定义类来存储电话和区域代码
public class PhoneNumber {
@NotEmpty
private String value;
@NotEmpty
private String locale;
}
@Phone Annotation 将用于注释字段以进行验证
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 它将检查手机对提供的区域代码的有效性
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;
}
}
}
用法
@Phone
private PhoneNumber phone;