Over a million developers have joined DZone.

Overriding Messages of Annotation-Based Validation in Spring

DZone's Guide to

Overriding Messages of Annotation-Based Validation in Spring

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

I 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.

Are you using Bitbucket to accomplish your company's mission? Share your company’s mission with #Forthecode for a chance to be featured on our homepage, our social media channels, or win a free t-shirt!


Published at DZone with permission of Shan Arshad, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}