Form Validation – part 2 (customizing error messages using Spring MessageSource)

Customising error messages using Spring MessageSource

In this article we will see how to provide a more meaningful validation message for the previous validation that provided a default validation message.

To achieve this we need to add below to Student.java

@Size(min=3, max=25,message = “Please enter a value for Student Hobby field between 5 and 25 characters”)
private String studentHobby;

now when we submit the same form with characters less than 5 in hobby field ,application will display the custom message  instead of default message.

validationMsg1

But in Web Application we prefer to keep the messages in a property file so let see ho we do that

We would require to add a property file [studentmessages] in our WEB-INF directory and then add the message as below in the property file.

validationMsg2

and in our Student.java we will remove the error message and keep only the min and max values as below;

@Size(min=3, max=25)
private String studentHobby;

While searching for a validation message ,Spring MVC would search for a key matching with this key pattern-
[Validation Annotation Name].[Object Reference Name].[Field Name]
for our application it is,Size.student1.studentHobby

In case if doesn’t find such key then again it would search for
[Validation Annotation Name].[Field Name]
eg:-Size.studentHobby

Again if it doesn’t find any key the it will search for this pattern-
[Validation Annotation Name].[Field Type]
eg:-Size.java.lang.String

Again if it does’nt find any key the it will search for this pattern-
[Validation Annotation Name]
eg in our cae,Size

If it still doesn’t find it then Spring will use the default error message provided by the Spring Framework.

Next restart the application and test it by submitting the form as earlier.


   

Comments are closed