If I use two user annotations in jsr 303, how do I stop validation for the second annotation if the validation fails first?

I have the following problem when working with jsr303:

i field is annotated as follows:

@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 the field passed the check for @NotEmpty. How can I check for two annotations? thanks in advance

+6
source share
2 answers

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.

+2
source

Therefore, after much research, I found one thing:

if you use different validators, you must make sure that they do not check the same rule. For example, if I write @PostCode, I have to be sure that an empty value is valid for this annotation. In this case, I will receive the message that I was expecting. So that the validator should only check a small part of the logic? other values ​​must be valid ...

If you cannot prevent this, the best way is to use groups for some messy situations.

Hope this helps someone ...

+1
source

Source: https://habr.com/ru/post/909835/


All Articles