自定义Validator注解

问题场景

在使用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;

当注入的手机号不合法时则抛出异常,异常信息则是在定义注解时的默认错误信息(因为此处并没有指定错误信息)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值