对于那些正在寻找使用libphone号码的电话号码的自定义验证器的人
电话号码.java库号码需要区域设置进行验证,因此我们需要创建一个自定义类来存储电话和区域代码
public class PhoneNumber {
@NotEmpty
private String value;
@NotEmpty
private String locale;
}
@Phone 注释将用于注释用于验证的字段
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 {};
}
电话号码验证器.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;