控制验证注释的顺序? [英] Control validation annotations order?

查看:158
本文介绍了控制验证注释的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有两个验证注释的字段

  @NotEmpty 
@Length(min = 3,max = 100)
字符串firstName;

我只是想知道hibernate是如何指定首先执行的验证注释的顺序,并且如果可以自定义的话?



我要问的原因是,如果我将该字段留空,则有时显示的第一个验证消息不是空的,而是其他时间



预先感谢。

解决使用JSR-303验证组。



如果没有指定组,则约束是Default Bean Validation组的一部分(请参阅: b
$ b

创建一个界面作为你的扩展(或任何你想要的调用它)group:

  public interface Extended {} 

现在创建一个接口,它将包含 javax.validation.GroupSequence 注释。

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

在约束上设置验证组

  @NotEmpty //如果没有指定组,则它是默认组的一部分
@Length(min = 3,max = 100,groups = Extended.class)
String firstName;

将MySequence传递到您的验证器调用。

  validator.validate(object,MySequence.class); 

由您的 @GroupSequence 指定,默认首先会验证约束条件,如果没有遇到违规违规行为,它将转到扩展组。


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.

解决方案

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.

这篇关于控制验证注释的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆