Search code examples
javabean-validationhibernate-validator

Java Bean validation: Combine two contstraints with OR on one field


I want to validate a field 'foo' against either of two constraints, i.e. something like this

@ConstraintA OR @ConstraintB
private String foo;

Is this possible?


Solution

  • This is possible with Hibernate Validator, but only using a Hibernate Validator specific extension. Using it is not standard conform to Bean Validation.

    You will have to use boolean composition of constraints as described here - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-boolean-constraint-composition

    You will need a "wrapper" constraint. Something like this:

    @ConstraintComposition(OR)
    @PConstraintA
    @ConstraintB
    @ReportAsSingleViolation
    @Target({ METHOD, FIELD })
    @Retention(RUNTIME)
    @Constraint(validatedBy = { })
    public @interface ConstraintAOrB {
        String message() default "{com.acme.ConstraintAOrB.message}";
    
        Class<?>[] groups() default { };
    
        Class<? extends Payload>[] payload() default { };
    }