字段检查非空才使用正则检查类

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotBlankThenPattern.NotBlankThenPatternValidation.class)
@Documented
public @interface NotBlankThenPattern {

    String regexp() default "";

    String message() default "格式错误";

    /**
     * @return the groups the constraint belongs to
     */
    Class[] groups() default {};

    /**
     * @return the payload associated to the constraint
     */
    Class[] payload() default {};


    class NotBlankThenPatternValidation implements ConstraintValidator {

        private Pattern pattern;

        @Override
        public void initialize(NotBlankThenPattern constraintAnnotation) {
            this.pattern = Pattern.compile(constraintAnnotation.regexp());
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (StringUtils.isBlank(value)) {
                return true;
            }
            return pattern.matcher(value).matches();
        }
    }
}

使用方法:

当ip为空时不会安装正则进行检查不为空时才按照正则检查

你可能感兴趣的:(1024程序员节)