How to set check order for JSR303 bean validation

本小妞迷上赌 提交于 2019-11-30 10:20:16

Yes Bean Validation supports this feature. It is called validation groups and group sequences. Groups are simple marker interfaces, for example you could create the two interfaces First and Second and change your code to something like this:

@NotBlank(groups = First.class)
@Size(min = 4, max = 30, groups = Second.class)
private String name;

Then you can define a group sequence:

@GroupSequence({ First.class, Second.class})
interface All {
}

Get hold of the Validator and call validator.validate(myObject, All.class)

It's all in the documentation.

The order of validation related annotations / constraints cannot be specified at time of writing this answer. I've submitted order related issue to Hibernate Validator team a time ago, the issue was was accepted and probably will be solved in a next Bean Validation specification release - see more details here: http://beanvalidation.org/proposals/BVAL-248/ Btw, in simple cases you can avoid "order conflict" by using "non conflicting" combinations of annotations, e.g. NotNull and Size - Size will evaluate to true for null value.

Have you considered to define two sequences. One for name and one for mail?

@GroupSequence({NameFirst.class, NameSecond.class})
interface AllName {
}

@GroupSequence({MailFirst.class, MailSecond.class, MailThird.class})
interface AllMail {
}

In this case you would call the validator like this:

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