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:
javax.validation
(build file: pom.xml
).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" value="classpath:validation-errors" /> </beans:bean>
validation-errors.properties
file with the following sample content in your root resources location. You may add as many error messages into it as you like.error.invalid={0} is in invalid format. error.required={0} is required.
Validator
class, TaskValidator
:public class TaskValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return clazz.isAssignableFrom(Task.class); } @Override public void validate(Object target, Errors errors) { Task task = (Task) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.required", new Object[] { "Task name" }); ValidationUtils.rejectIfEmpty(errors, "createdBy.id", "error.required", new Object[] { "Created user" }); } }
TaskValidator
class inside the TaskController
class using InitBinder
:@InitBinder("task") public void initBinder(WebDataBinder binder) { binder.addValidators(new TaskValidator()); }
ModelAttribute
with the @Valid
annotation of javax.validation.Valid
in the handler method.createNewTask()
method listed in the previous section.<form:errors/>
tag for each form field you are validating—as seen in the /tasks/new.jsp
file.The form will look like this in case of validation errors: