@Constraint 自定义注解校验手机号
@Constraint 自定义注解校验手机号
自定义注解
/**
* 手机号校验
* @author lkb
* @date 2021/4/12
*/
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Constraint(validatedBy = {PhoneValidator.class})
public @interface PhoneValid {
String message() default "手机格式异常";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
校验规则
/**
* @Description 手机校验
* @Author lkb
* @CreateDate: 2021/4/12
*/
@Slf4j
public class PhoneValidator implements ConstraintValidator<PhoneValid, String> {
private static final int PHONE_LENGTH =11;
private static final Pattern pattern = Pattern.compile("^[1]\\d{10}$");
@Override
public boolean isValid(String phone, ConstraintValidatorContext context) {
if(StrUtil.isBlank(phone)){
log.warn("PhoneValidator phone is blank, phone = {}", phone);
return false;
}
if(phone.length() != PHONE_LENGTH){
log.warn("PhoneValidator phone length valid fail, phone = {}", phone);
return false;
}
if(!pattern.matcher(phone).matches()){
log.warn("PhoneValidator phone pattern valid fail, phone = {}", phone);
return false;
}
return true;
}
}
使用
/**
* 账号
*/
@PhoneValid
private String account;
欢迎关注我的公众号 -- 大白和小倔