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="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:messages" /> </bean> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="validationMessageSource" ref="messageSource"/> </bean>
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; }
POM
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.
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency>
Customize error message
@Email @NotBlank(message = "{error.not.blank}") private String email; // code omitted
Properties files
error.not.blank = Please don't leave blank