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" value="classpath:validation-errors" />
    </beans:bean>
  3. 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 into it as you like.
    error.invalid={0} is in invalid format.
    error.required={0} is required.
  4. Create a 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" });
       }
    }
  5. Register the TaskValidator class inside the TaskController class using InitBinder:
    @InitBinder("task")
    public void initBinder(WebDataBinder binder) {
       binder.addValidators(new TaskValidator());
    }
  6. Annotate ModelAttribute with the @Valid annotation of javax.validation.Valid in the handler method.
  7. Handle validation errors in the request handler method, as given in the createNewTask() method listed in the previous section.
  8. Add a <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:

Validating forms
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset