简体   繁体   English

Hibernate验证程序在消息中显示自定义元素名称

[英]Hibernate validator show custom element name in message

I'm using Hibernate validation in my Spring webapp. 我在Spring Web应用程序中使用了Hibernate验证。 I currently have everything configured as completely default, and I have created a ValidationMessage.properties file that I intend to fill with custom messages. 我目前已将所有内容配置为完全默认,并且我创建了ValidationMessage.properties文件,打算用自定义消息填充该文件。

For all my Google-ing, I can't find the answer to what I believe should be a fairly simple question - what is the best way to get a nicely printed element name alongside the error text? 对于我所有使用Google的人,我都无法找到我认为应该是一个非常简单的问题的答案-在错误文本旁边获得漂亮打印的元素名称的最佳方法是什么?

For example, for the below messages, I would want it to say "Old password cannot be empty" and "New Password cannot be empty" 例如,对于以下消息,我希望它说“旧密码不能为空”和“新密码不能为空”

<form:input path="oldPassword"/>
<form:input path="newPassword"/>

Is it possible to add my own attributes to the @NotEmpty annotation and then refer to them in my custom message? 是否可以将我自己的属性添加到@NotEmpty批注,然后在我的自定义消息中引用它们?

@NotEmpty(nicename="Old Password")
private String oldPassword;

@NotEmpty(nicename="New Password")
private String newPassword;

And then in the properties file just refer to it like this - 然后在属性文件中像这样引用它-

org.hibernate.validator.constraints.NotEmpty.message=${nicename} cannot be empty

Well, you can do it other way around, so 好吧,您可以以其他方式做到这一点,所以

@NotEmpty(message="{nicename} cannot be empty")

And add a property with a nicename key in ValidationMessages. 并在ValidationMessages中添加一个带有nicename键的属性。 By the way, a great article about using the custom messaging in spring. 顺便说一句,一篇很棒的文章介绍了在春季使用自定义消息传递。 It doesn't discuss your particular case, but surely helpful 它没有讨论您的特殊情况,但肯定有帮助

http://www.silverbaytech.com/2013/04/16/custom-messages-in-spring-validation/ http://www.silverbaytech.com/2013/04/16/custom-messages-in-spring-validation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM