问题场景
在使用Validator插件对参数进行校验时,虽然有很多的校验注解可以使用,但是远远不能满足我们的需求,虽然也可以通过 @Pattern() 注解使用正则表达式进行匹配校验,但是一个字段的校验往往需要很长的正则表达式,例如对手机号进行校验,则使用 @Pattern() 注解时如下:
@Pattern(regexp="^1[3|4|5|7|8][0-9]{9}$")
String phone;
如果多处使用时每次都这么校验很不优雅。
自定义注解@Phone
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
//表明由PhoneParse类来验证注解
@Constraint(validatedBy = PhoneParse.class)
public @interface Phone {
//默认错误信息
String message() default "手机号不合法!";
//默认校验正则表达式
String regexp() default "^1[3|4|5|7|8][0-9]{9}$";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定义注解验证码对注解进行校验
public class PhoneParse implements ConstraintValidator<Phone, Object> {
//测试类,测试正则表达式是否满足手机号的校验规则
public static void main(String[] args) {
String regexp = "^1[3|4|5|7|8][0-9]{9}$";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher("手机号");
System.out.println(matcher.matches());
}
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
ConstraintValidatorContextImpl con = (ConstraintValidatorContextImpl) constraintValidatorContext;
//获取注解中的属性值
Map<String, Object> map = con.getConstraintDescriptor().getAttributes();
//获取验证时使用的正则表达式,如果没写则使用默认的
String regexp = (String) map.get("regexp");
String param = (String) o;
Pattern pattern = Pattern.compile(regexp);
Matcher m = pattern.matcher(param);
return m.matches();
}
}
代码实际应用
@Phone
String phone;
当注入的手机号不合法时则抛出异常,异常信息则是在定义注解时的默认错误信息(因为此处并没有指定错误信息)