同一属性上的不同 Hibernate 验证注释
我在 bean 中的属性上使用两个验证注释:
@NotEmpty(message = "{name.required}")
@Pattern(regex = "^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$", message = "{invalid.name}")
private String name;
如果我将名称留空,则会收到两个错误,但我只想要第一个错误消息 (如果第一个条件发生,则显示其错误消息,然后跳过第二个条件)。
I am using two validation annotations on a property in the bean:
@NotEmpty(message = "{name.required}")
@Pattern(regex = "^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$", message = "{invalid.name}")
private String name;
If i left the name empty, I got the two errors but I want only the first error message
(if the first condition occurs show its error message then skip the second condition).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以通过创建复合约束并使用 @ReportAsSingleViolation 元约束对其进行注释来完成。
UserName.java
参考
This can be done by creating Composite Constraint and annotating it with @ReportAsSingleViolation meta constraint.
UserName.java
Reference 3.2. Constraint composition
接受的答案并不按您的预期工作。仅当您想要列出 ENTIRE 组合链中的 ALL 错误时,确定约束组合才是好的。如果您想提前退出第一个验证错误,则它不起作用。
@ReportAsSingleViolation
的文档表示忽略每个单独的组合约束的错误报告。使用accept示例
这意味着您将收到
UserName
注释的默认消息错误,即“无效的userName!”即使 @NotEmpty 首先失败......我必须说我对 java bean 验证实现者的设计如此糟糕感到非常震惊。如果您返回完全不相关的消息,那么组合验证绝对没有意义。它应该首先失败并返回实际失败的验证的相应错误!无论如何,如果没有大量丑陋的黑客攻击,就没有办法做到这一点。如此简单的验证任务变成了一场噩梦。 0_o
我的解决方案是不要编写验证,只需创建 1 个验证并自行实现。它不干燥,但至少很简单。
}
The accepted answer doesn't work as you expect. Sure constraint composition is good only if you want to list ALL the errors in the ENTIRE composition chain. It doesn't work if you want to early exit from the first validation error.
The docs for
@ReportAsSingleViolation
say The error reports of each individual composing constraint are ignored.Using the accept example
This means you will get the default message error of the
UserName
annotation which is "invalid userName!" even if @NotEmpty fails first....I must say I am quite shocked at how poor this design is by the java bean validation implementors. It makes absolutely no sense to have composed validations if you return a completely irrelevant message. It should fail first AND return the corresponding error for the validation that actually failed!. Anyway there is no way to do this without massive ugly hacks. Such a simple validation task turns into a nightmare. 0_o
My work around solution is don't compose validations, just create 1 validation and implement it all yourself. Its not DRY but its simple at least.
}