Hibernate Validator 布尔逻辑

Hibernate Validator boolean logic

我正在研究在 AND'ing 约束不够的情况下,使用 Hibernate Validator 对我的 bean 验证使用布尔逻辑。我发现可以通过使用 @ConstraintComposition 注释作为 described in the documentation 创建新注释来更改此默认行为。该文档提供了以下示例。

@ConstraintComposition(OR)
@Pattern(regexp = "[a-z]")
@Size(min = 2, max = 3)
@ReportAsSingleViolation
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
public @interface PatternOrSize {
    String message() default "{org.hibernate.validator.referenceguide.chapter11." +
            "booleancomposition.PatternOrSize.message}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

使用此 @PatternOrSize 验证约束意味着输入字符串 或者 小写 的大小介于 2 和 3 之间. 现在这提出了几个问题:

提前致谢。

I believe one has to create a new annotation to change the default boolean logic behavior. Is this correct?

是的,没错。

Is it possible to further customize the boolean logic behavior without creating a custom validator, e.g. defining AND and OR at the same time?

您可以尝试创建一个分层组合的约束(即由其他约束组成的约束),它在不同级别使用 AND 和 OR。我还没有尝试过(我不认为我们有测试)但它可能值得一试。不过,根据所需的布尔逻辑,它可能不适合您的用例。

is it possible to make the arguments to the @Pattern and @Size constraints dynamic?

是的,您可以通过 @OverridesAttribute:

@ConstraintComposition(OR)
@Pattern(regexp = "[a-z]")
@Size(min = 2, max = 3)
@ReportAsSingleViolation
@Target({ METHOD, FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
public @interface PatternOrSize {

    String message() default "...";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

    @OverridesAttribute(constraint=Size.class, name="min")
    int min() default 0;

    @OverridesAttribute(constraint=Size.class, name="max")
    int max() default Integer.MAX_VALUE;

    @OverridesAttribute(constraint=Pattern.class, name="regexp")
    String regexp();
}