@Pattern
还是有不同的方法呢?@Pattern
是最佳选择,那么regex
是什么?@Pattern
注释吗?答案 0 :(得分:5)
我想在bean验证中验证字符串是否完全匹配。我应该使用@Pattern还是有不同的方法呢?
您可以使用@Pattern
或非常轻松地实施自定义约束:
@Documented
@Constraint(validatedBy = MatchesValidator.class)
@Target({ METHOD, CONSTRUCTOR, PARAMETER, FIELD })
@Retention(RUNTIME)
public @interface Matches {
String message() default "com.example.Matches.message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value();
}
使用这样的验证器:
public class MatchesValidator implements ConstraintValidator<Matches, String> {
private String comparison;
@Override
public void initialize(Matches constraint) {
this.comparison = constraint.value();
}
@Override
public boolean isValid(
String value,
ConstraintValidatorContext constraintValidatorContext) {
return value == null || comparison.equals(value);
}
}
如果
@Pattern
是最佳选择,那么regex
是什么?
基本上只是你要匹配的字符串,你只需要转义特殊字符,如[\ ^ $。|?* +()。有关详细信息,请参阅this reference。
我可以在同一个字段上为两个不同的组使用两个@Pattern注释吗?
是的,只需使用@Pattern.List
注释:
@Pattern.List({
@Pattern( regex = "foo", groups = Group1.class ),
@Pattern( regex = "bar", groups = Group2.class )
})