I have the next issue while working with jsr303:
i have field annotated the next way:
@NotEmpty(message = "Please specify your post code")
@PostCode(message = "Your post code is incorrect")
private String postCode;
But I need to check @PostCode only if field passed the validation for @NotEmpty. How can I checking for tese two annotations? Thanks in advance
You can use validation groups to execute validations group-wise. For details, see section 3.4. Group and group sequence in JSR-303. In your sample you would 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 validating you would call validation for the default group, then if no errors occurred, 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 would be to make all validations (if you can afford it), and then manually filter out multiple validation errors for the same field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With