Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I use two custom annotations in jsr 303 how to stop validation for second annotation if validation failed on first?

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

like image 952
user1240290 Avatar asked Mar 02 '12 15:03

user1240290


1 Answers

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.

like image 145
MicSim Avatar answered Nov 12 '22 05:11

MicSim