You can use validation groups to perform validations on groups. See Section 3.4 for details . Group and group sequence in JSR-303 . In your example, you will do something like:
@NotEmpty(message = "Please specify your post code") @PostCode(message = "Your post code is incorrect", groups = Extended.class) private String postCode;
And when checking, you call checking for the default group, and then, if there were no errors, for the Extended
group.
Validator validator = factory.getValidator(); Set<ConstraintViolation<MyClass>> constraintViolations = validator.validate(myClass, Default.class); if (constraintViolations.isEmpty()) { constraintViolations = validator.validate(myClass, Extended.class); }
You can do much more using validation groups.
An alternative could be all checks (if you can afford it), and then manually filter out a few check errors for the same field.
source share