JSR303(hibernate-validator)自定义注解校验

自定义注解校验


以校验手机号为例,自定义 @IsPhone来验证是否是手机号:

编写注解:

//说明该注解将被包含在javadoc中
@Documented
// 注解的作用目标 类上、方法上、属性上
@Target({ElementType.FIELD, ElementType.PARAMETER})
// 注解的保留位置  
@Retention(RetentionPolicy.RUNTIME)
// 校验注解必须使用@Constraint
@Constraint(validatedBy = IsPhoneValidator.class)
public @interface IsPhone {
    boolean required() default true;
    String message() default "手机号不正确";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

编写校验逻辑:

public class IsPhoneValidator implements ConstraintValidator<IsPhone, String> {

    private boolean required;

	// 重写initialize方法获取注解实例
    @Override
    public void initialize(IsPhone ca) {
    	// 重注解实例中获信息
        required = ca.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
    	// value就是要校验的数据了
        if (value != null && required) {
            // 手机号校验规则
            System.out.println(value);
            String regexp= "^(((\\+\\d{2}-)?0\\d{2,3}-\\d{7,8})|((\\+\\d{2}-)?(\\d{2,3}-)?([1][3,4,5,7,8][0-9]\\d{8})))$";
            boolean matches = Pattern.matches(regexp, value);
            System.out.println(matches);
            return matches;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq122516902/article/details/85125750