/**
* 自定义注解 字段非空时才按照正则校验
* @author dxy
* @version 1.0
* @date 2022/3/21 11:39
* @descrition
* @Version 1.0
*/
({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
(RetentionPolicy.RUNTIME)
(validatedBy = NotBlankThenPattern.NotBlankThenPatternValidation.class)
public @interface NotBlankThenPattern {
String regexp() default "";
String message() default "参数格式错误";
Class<? extends Payload>[] payload() default {};
class NotBlankThenPatternValidation implements ConstraintValidator<NotBlankThenPattern, String> {
private Pattern pattern;
public void initialize(NotBlankThenPattern constraintAnnotation) {
this.pattern = Pattern.compile(constraintAnnotation.regexp());
}
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;