Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Overriding Messages of Annotation-Based Validation in Spring

DZone's Guide to

Overriding Messages of Annotation-Based Validation in Spring

· Java Zone ·
Free Resource

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

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.

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}