简体   繁体   中英

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

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

@ConstraintA OR @ConstraintB
private String foo;

Is this possible?

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 { };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM