Validating forms

Spring MVC makes form validation a lot easier using Spring's Validator framework. You might have noticed the @Valid annotation and the usage of the BindingResult.hasErrors() method call inside handler methods listed in the previous section. They are part of the validation framework.

Let's create a validator for a Task object by following these steps:

  1. Add the Validation API's Maven dependency, javax.validation (build file: pom.xml).
  2. Make sure you have defined MessageSourceBean for the validation-errors properties file in your bean definition:
    <beans:bean id="messageSource" class="org.springframework.context. support.ReloadableResourceBundleMessageSource"> <beans:property name="defaultEncoding" value="UTF-8" /> <beans:property name="basenames" ...

Get Spring MVC: Designing Real-World Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.