简体   繁体   中英

Hibernate validator show custom element name in message

I'm using Hibernate validation in my Spring webapp. I currently have everything configured as completely default, and I have created a ValidationMessage.properties file that I intend to fill with custom messages.

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?

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(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. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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