Bootstrap

@Pattern参数校验增强工具类@NotBlankThenPattern

/**
 * 自定义注解 字段非空时才按照正则校验
 * @author dxy
 * @version 1.0
 * @date 2022/3/21 11:39
 * @descrition
 * @Version 1.0
 */
@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 "参数格式错误";
    Class<? extends Payload>[] payload() default {};
    class NotBlankThenPatternValidation implements ConstraintValidator<NotBlankThenPattern, String> {
        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();
        }
    }
}

使用:

/**
 * 邮箱地址
 */
@ExcelProperty(index=8,value ="邮箱")
@Length(max = 200,message = "邮箱长度超过规定长度200")
@NotBlankThenPattern(regexp = ExcelPatternMsg.EMAIL,message = ExcelPatternMsg.EMAIL_MSG)
@ApiModelProperty("邮箱地址")
private String email;
;