Overriding Messages of Annotation-Based Validation in Spring
Join the DZone community and get the full member experience.
Join For FreeI was working on a project which is developed in Spring 3.0.
That project was almost completed and we have been using Annotation based validation for form fields mapped to that bean. We have been displaying messages to users by using annotation property “message.” Below is an example of it.
@Size(min = 1, max = 50, message = "Email size should be between 1 and 50") private String loginId;
Now i have to shift all those error messages in properties files of all languages so that error messages will be loaded from properties files if user has changed the language.
Below are the steps of doing that.
@Size(min = 1, max = 50, message = "Email size should be between 1 and 50") private String loginId;
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) private String 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.
This is the tricky part where I was making a mistake. Traditionally in properties file we will be defining the property name and a message against it.
loginForm.loginId=email shouldn't be empty.
But in annotations case Spring caters it differently. In this scenario spring makes its own string as key to its property file message if no error message has been given in annotation.
Below is the formula which spring uses to define a key of a property.
Size(@Size) = validation annotation name loginForm = My Class Name loginId = Property name in LoginForm class.
Published at DZone with permission of Shan Arshad, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Azure Virtual Machines
-
How AI Will Change Agile Project Management
-
How to Use an Anti-Corruption Layer Pattern for Improved Microservices Communication
-
Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
Comments