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:
Add the Validation API's Maven dependency,
javax.validation
(build file:pom.xml
).Make sure you have defined
MessageSourceBean
for thevalidation-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" value="classpath:validation-errors" /> </beans:bean>
Make sure there is a
validation-errors.properties
file with the following sample content in your root resources location. You may add as many error messages...