Wednesday, 27 July 2011

Adding a JSR 303 Custom Constraint to your Spring 3 Web App

In yesterday’s blog, I demonstrated how to write a JSR 303 Custom Constraint and validate it use Hibernate’s reference validator class javax.validation.Validator. Having written your constraint, the next step is to add it into your web-application, which couldn’t be easier.
There are three very simple steps involved:
  1. Ensure that your newly written, fully tested constraint is on your web-app’s classpath
  2. Annotate your bean with your constraint:

    public class JSRValidatedAddress {

    @BirminghamPostCode(message = "This must be a Birmingham post code")
    private String postCode;

    // Reset of the code ommited for clarity
  3. Use the @Valid annotation to mark your bean for validation

      @RequestMapping(value = PATH, method = RequestMethod.POST)
    public String addAddress(@Valid JSRValidatedAddress address, BindingResult result,
          Model model
    ) {
This all works because the Hibernate validator will scan the entire classpath, picking up constraints of any type. All this means that you DO NOT need to use the @InitBinder annotation; the two methods do not mix.

No comments: