3
  1. 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?
  2. If @Pattern is the way to go, what is the regex?
  3. Can I use two @Pattern annotation for two different groups on a same field?
4

1 回答 1

8

我想在 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

基本上就是要匹配的字符串,只需要转义[\^$.|?*+()等特殊字符即可。有关详细信息,请参阅此参考。

我可以为同一字段上的两个不同组使用两个 @Pattern 注释吗?

是的,只需使用@Pattern.List注释:

@Pattern.List({
    @Pattern( regex = "foo", groups = Group1.class ),
    @Pattern( regex = "bar", groups = Group2.class )
})
于 2013-07-05T18:03:35.610 回答