注解:BlankOrPattern.java
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.Pattern;
/**自定义注解
* 验证器 当 当字段不为null且长度>0 才执行正则校验
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {BlankOrPatternValidator.class})
public @interface BlankOrPattern {
String regexp();
Pattern.Flag[] flags() default {};
String message() default "{javax.validation.constraints.Pattern.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface List {
Pattern[] value();
}
public static enum Flag {
UNIX_LINES(1),
CASE_INSENSITIVE(2),
COMMENTS(4),
MULTILINE(8),
DOTALL(32),
UNICODE_CASE(64),
CANON_EQ(128);
private final int value;
private Flag(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
}
验证器:BlankOrPatternValidator.java
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Pattern.Flag;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;
/**
* 验证器 当字段不为null且长度>0 才执行正则校验
*/
public class BlankOrPatternValidator implements ConstraintValidator<BlankOrPattern, String> {
private static final Log log = LoggerFactory.make();
private java.util.regex.Pattern pattern;
public BlankOrPatternValidator() {
}
@Override
public void initialize(BlankOrPattern parameters) {
Flag[] flags = parameters.flags();
int intFlag = 0;
Flag[] arr$ = flags;
int len$ = flags.length;
for(int i$ = 0; i$ < len$; ++i$) {
Flag flag = arr$[i$];
intFlag |= flag.getValue();
}
try {
this.pattern = java.util.regex.Pattern.compile(parameters.regexp(), intFlag);
} catch (PatternSyntaxException var8) {
throw log.getInvalidRegularExpressionException(var8);
}
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if (value == null ||value.length() == 0) {
return true;
} else {
Matcher m = this.pattern.matcher(value);
return m.matches();
}
}
}
参考 https://blog.csdn.net/qq_16909139/article/details/107056445