Bean验证用于精确字符串匹配

时间:2013-07-05 16:42:51

标签: java regex javabeans bean-validation

  1. 我想在bean验证中验证字符串是否完全匹配。我应该使用@Pattern还是有不同的方法呢?
  2. 如果@Pattern是最佳选择,那么regex是什么?
  3. 我可以在同一个字段中为两个不同的组使用两个@Pattern注释吗?

1 个答案:

答案 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 )
})