Conditionally prevent cascading validation

和自甴很熟 提交于 2019-12-11 09:45:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/30396714/conditionally-prevent-cascading-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!