Reputation: 1976
I'm working on a Spring MVC project in which I'm using Hibernate Validator to validate input fields from a form. As my project is Maven-based, I added this dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>4.1.0.Final</version>
</dependency>
The form validation process works fine but now, I would like to override or internationalize the default error messages.
For instance, by default, using the @NotEmpty annotation will yield the message "may not be empty". How I can replace this message by my own message? I've tried several solutions:
But the default messages are still displayed...
Any hint? Thx in advance.
Upvotes: 4
Views: 9405
Reputation: 151
This is a bit explanation that how you can find the exact property name behind every annotation given or used for validation. See below mentioned steps.
@Size(min = 1, max = 50, message = "Email size should be between 1 and 50")
Now remove { message = "Email size should be between 1 and 50" } from validation tag.
After doing this your annotation will be like this.
@Size(min = 1, max = 50)
Now at controller side debug the method which is being called upon when submitting the form. Below is my method which is receiving the request when user hits submit.
public static ModelAndView processCustomerLoginRequest(IUserService userService,LoginForm loginForm,
HttpServletRequest request, HttpSession session, BindingResult result, String viewType, Map<String, LoginForm> model)
Now place a debug point at very first line of the method and debug the argument "result".
BindingResult result
While dubugging you will find a string like this in codes array.
Size.loginForm.loginId
Now define this string in your properties file and a message against that string. Compile and execute. That message will be displayed whenever that annotation wouldn't be validated.
Size.loginForm.loginId=email shouldn't be empty.
Basically spring makes its own string as key to its property file message. In above key
Size(@Size) = validation annotation name
loginForm = My Class Name
loginId = Property name in LoginForm class.
The Beauty of this method is it also runs fine while you will be using Spring Internationalization. It automatically switches the messages file as language changes.
Upvotes: 1
Reputation: 4483
Yes you can do that. You can load the error message from the properties files. But you need to have the key in a proper format. Like NotEmpty.ClassName.fieldName=fieldName Can not be empty
.
You just need to specify your exact class name and property name in your properties files. Everything other is looking just perfect in your case.
You can also have a common error message for a particular type of validation annotation for all the fields having that annotation. Like javax.validation.constraints.NotNull=Notnull erro happened!
Hope this helps you. Cheers.
Upvotes: 5