Control validation annotations order?

*爱你&永不变心* 提交于 2019-12-17 18:55:00

问题


i have a field that have two validation annotations

@NotEmpty
@Length(min=3,max=100)
String firstName;

i am just curious to know how hibernate is specifying the order of which validation annotation to be executed first, and if it's possible to custom that ?

the reason i am asking is that if i left that field empty sometimes the first validation message displayed is for not empty and other times if i left it empty i get the validation message for the length annotation.

thanks in advance.


回答1:


Use JSR-303 validation groups.

If no groups are specified a constraint is part of the Default Bean Validation group (see: javax.validation.groups.Default).

Create an interface to be your "Extended" (or whatever you want to call it) group:

public interface Extended{}

Now create an interface that will have the javax.validation.GroupSequence annotation.

@GroupSequence({Default.class, Extended.class})
public interface MySequence {}

Set the validation groups on your constraints

@NotEmpty // If no group is specified it is part of the default group
@Length(min=3,max=100, groups = Extended.class)
String firstName;

Pass MySequence to your validator call.

validator.validate(object, MySequence.class);

As specified by your @GroupSequence the default constraints will be validated first and if no contraint violations are encountered it will move on to the extended group.



来源:https://stackoverflow.com/questions/5571231/control-validation-annotations-order

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