Given the classes:
class Foo {
@Size(max = 1)
@Valid
private List<Bar> bars;
}
class Bar {
@NotBlank
private String snafu;
}
How can validation be applied that prevents Bar.snafu being validated when the Size constraint on Foo.bars failed?
I though that i can achieve that with group conversion and the definition of a group sequence. but i failed configuring it the way i want.
Even though it looks like, defining fail-fast is not an option.
The following solves this issue:
interface Advanced {}
@GroupSequence({Default.class, Advanced.class})
interface Sequence {}
class Foo {
@Size(max = 1)
@Valid
private List<Bar> bars;
}
class Bar {
@NotBlank(groups = Advanced.class)
private String snafu;
}
Foo foo = new Foo();
foo.bars = new ArrayList<Bar>();
foo.bars.add(new Bar());
foo.bars.add(new Bar());
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Foo>> constraintViolations = validator.validate(foo, Sequence.class)
Now if there are more Bar instances then allowed (Size constraint) only a constraint violation of the size constraint is generated.