Spring MVC Form Validation Tutorial (With Annotations and ResourceBundle)

In our previous Spring MVC Validation with annotation tutorial we have learnt how to use JSR303 Bean Validation to validate our Spring MVC Forms. There you could see the validation messages are added on the bean constraints itself @NotEmpty(message=“FirstName cannot be empty”) but that is not the way we code in the real world situation. Messages will be added to a property file separately so that we don’t have to restart the server every time when we modify the validation message or when we add a new message. Let’s see how to do validation with ResourceBundle.

Every thing resembles the same as my previous tutorial except we need to add a entry in the SpringConfig-servlet.xml and new property file.


 <beans xmlns="http://www.springframework.org/schema/beans" 
xsi:schemaLocation=" http://www.springframework.org/schema/beans%20
 <context:component-scan base-package="com.jackson"></context:component-scan>
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/Jsp/"></property>
 <property name="suffix" value=".jsp"></property>
 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
 <property name="basename" value="props"></property>

In our configuration file we have added an entry for the messageSource , which has the property basename whose value is “props” that should be the name for our property file which contains validation error messages.


NotEmpty.rb.firstName=FirstName cannot be empty
Size.rb.firstName=Size should be between 1 to 6
NotEmpty.rb.email=Email Address cannot be empty
Email.rb.email=Please enter a valid email address
Size.rb.lastName=Size should be between 1 to 6

Property has to be framed as below.

NotEmpty     .        rb                        . firstName   =  FirstName cannot be empty

Constraint. ModelAttribute . Variable  = Custom message

The property has 4 main parts

  1. Validation Constraints applied on our bean.
  2. ModelAttribute used in our controller.
  3. Variable in our bean for which we have applied the constraints
  4. Custom message which has to be displayed when validation errors occurs.

Lets run our application




Leave a Reply

Your email address will not be published. Required fields are marked *