Barebones Spring MVC part 3: Form validation

August 15, 2010

In any real-world web application, some interaction with the user is likely to call for input of information which must be validated. This often includes email addresses, phone numbers, and so forth. JSR-303 Bean Validation specifies annotations for declarative validation rules which can be standardized across the layers of an enterprise application, from the database to the user interface.

This example builds upon part 1: core to introduce server-side JSR-303-backed validation of an HTML form.

The following changes are required:

  1. Add the JSR-303 validation API javax.validation to the Maven POM.
  2. Add the @Valid annotation to controller method inputs.
  3. Add Errors objects to controller method inputs for view error binding.
  4. Add JSR-303 annotations to
  5. Add a JSR-303-backed Validator to the Spring context.
  6. Add a JSR-303 reference implementation hibernate-validator to the Maven POM.
  7. Add <form:errors /> elements to simpleForm.jsp.

There is only one controller method with input, to which the @Valid annotation is added. Errors objects are also added to the controller method input to provide error binding for the view.

@RequestMapping(value = "/simple", method = RequestMethod.POST)
public void simple(@Valid SimpleForm simpleForm, Errors errors, Model model) {
    model.addAttribute("value1", simpleForm.getValue1());
    model.addAttribute("value2", simpleForm.getValue2());
    model.addAttribute("value3", simpleForm.getValue3());

JSR-303 annotations are added to to limit the length of value1 and the pattern of value2.

@Size(min = 2, max = 6)
private String value1;

@Pattern(regexp = "Val.*C")
private String value2;

The Spring MVC namespace will automatically configure a JSR-303-backed Validator as long as it is present on the classpath.


<mvc:annotation-driven />

Finally, the Spring <form:errors /> element is added to the view to show validation errors.


    <td>Value 1:</td>
    <td><form:input path="value1" /> <form:errors path="value1" /></td>
    <td>Value 2:</td>
    <td><form:select path="value2" items="${values}" /> <form:errors path="value2" /></td>
    <td>Value 3:</td>
        Check 1: <form:checkbox path="value3" value="check1" /><br />
        Check 2: <form:checkbox path="value3" value="check2" /><br />
        Check 3: <form:checkbox path="value3" value="check3" /><br />
        <form:errors path="value3" />

When the form is submitted, the inputs are automatically validated, and any validation errors are displayed next to each corresponding input field in the form.