- 我想在 bean 验证中验证一个字符串是否完全匹配。我应该使用
@Pattern
还是有不同的方法? - 如果
@Pattern
是要走的路,regex
是什么? - 我可以对同一字段上的两个不同组使用两个
@Pattern
注释吗?
最佳答案
I want to validate a string for exact match in bean validation. Should I use @Pattern or is there a different method to do so?
您可以使用 @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();
}
像这样的 validator :
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);
}
}
If
@Pattern
is the way to go, what is theregex
?
基本上就是你要匹配的字符串,只需要对[\^$.|?*+()等特殊字符进行转义即可。参见 this reference了解更多详情。
Can I use two @Pattern annotation for two different groups on a same field?
是的,只需使用 @Pattern.List
注释:
@Pattern.List({
@Pattern( regex = "foo", groups = Group1.class ),
@Pattern( regex = "bar", groups = Group2.class )
})
关于java - 精确字符串匹配的 Bean 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17493503/