Reputation: 4805
Use-case: When adding/editing an address or setting a direct delivery address the form has the same fields. So it's good practice to use the address form class as a super class of the delivery form:
public class AddressForm {
@NotEmpty
private String name;
// ...
}
public class DeliveryForm extends AddressForm {
public static enum ShippingType {
DIRECT_SHIPPING,
// ...
}
@NotNull
private ShippingType shippingType;
// ...
}
Is it possible to create a custom constraint (validator) at class level to set the condition whether the super class should be validated or not?
Such as:
@ValidateSuperclassIf(field = "shippingType", value = "DIRECT_SHIPPING")
public class DeliveryForm extends AddressForm {
// ...
}
How to implement the javax.validation.ConstraintValidator<ValidateSuperclassIf, Object>.isValid(Object value, ConstraintValidatorContext context)
method then?
Upvotes: 1
Views: 2055
Reputation: 19109
Is it possible to create a custom constraint (validator) at class level to set the condition whether the super class should be validated or not?
No, you cannot. There are not means in Bean Validation (the spec) nor in the reference implementation Hibernate Validator to do so.
There are some discussions to have the ability to skip super type constraints (HV-548 and BVAL-256), but that would just generally disable them, not add conditional (de-)activiation.
Upvotes: 3