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.
So after long researches I found one thing:
if you use different validators, you have to ensure that they do not check the same rule. For example if I write @PostCode I have to be sure that empty value is valid for this annotation. In this case I'll receive the message I expected. So that validator have to check only small piece of logic? other values have to be valid...
If you can not prevent this, the best way is really to use groups for some messy situations..
Hope It would help someone....
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.