Bean Validation

Bean Validation

For spring mvc to enable form validation, follow the steps below.

Step 1 – LocalValidatorFactoryBean and ResourceBundle

You need to register LocalValidatorFactorBean and resouces bundle implementation to your application context.

<bean id="messageSource" class="">
  <property name="basename" value="classpath:messages" /> 

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  <property name="validationMessageSource" ref="messageSource"/> 


Step 2 – Define validator in your mvc:annotation-driven

<mvc:annotation-driven validator="validator" />

<bean id="messageSource" class="">
<bean id="validator" class="">

 .... // code omitted...


Step 3 – Apply annotation validation.

You can find some annotation from this post.


Step 4 – @Valid and BindingResult

The follow code is a sample programming idiom. The important part is annotation @Valid and BindingResult arguments, sequence and both must be present.

@RequestMapping(value = "/form", method = RequestMethod.POST)
public String formPost(@Valid @ModelAttribute("user") User user, 
                       BindingResult result, Model model) {
       String view = "resultView";

       if (result.hasErrors()) {
	   view = "formView";
       } else {
	   model.addAttribute("user", user);
       return view;



This is the library that required for the job done. I’m using spring platform, therefore i can simply ignore the version of hibernate-validator. Otherwise, you may need to include the version tag to specify the version.


 Customize error message

@NotBlank(message = "{error.not.blank}")
private String email;

// code omitted


Properties files 

error.not.blank = Please don't leave blank


Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.