Search code examples
javaspringannotationsconstraintshibernate-validator

How to user Hibernate @Valid constraint with Spring 3.x?


I am working on simple form to validate fields like this one.

public class Contact {

    @NotNull
    @Max(64)
    @Size(max=64)
    private String name;

    @NotNull
    @Email
    @Size(min=4)
    private String mail;

    @NotNull
    @Size(max=300)
    private String text;


}

I provide getter and setters hibernate dependencies on my classpath also.But i still do not get the how to validate simple form there is actually not so much documentation for spring hibernate combination.

@RequestMapping(value = "/contact", method = RequestMethod.POST)
public String add(@Valid Contact contact, BindingResult result) {
    ....
}

Could you explain it or give some tutorial , except original spring 3.x documentation


Solution

  • If you want to use the @Valid annotation to trigger the validation of your backing bean. Then it's not the Hibernate annotation it's javax.validation.Valid from the validation API.

    To get it running you need both:

    In my case I used a custom validator (RegistrationValidator) instead of annotating the form fields in the backing bean to do the validation. I need to set the I18N key's for the error messages that's the reason that I had to replace the Spring 3 MessageCodeResolver with my own. The original one from Spring 3 always tries to add type or field name to find the right key when it's not found in the first way.

    A little example:

    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.WebDataBinder;
    ...
    import javax.validation.Valid;
    
    @Controller
    public class RegistrationController
    {
        @InitBinder
        protected void initBinder(WebDataBinder binder) 
        {
            binder.setMessageCodesResolver(new MessageCodesResolver());
            binder.setValidator(new RegistrationValidator());
        }
    
        @RequestMapping(value="/userRegistration.html", method = RequestMethod.POST)
        public String processRegistrationForm(@Valid Registration registration, BindingResult result, HttpServletRequest request) 
    {
             if(result.hasErrors())
             {
                return "registration"; // the name of the view
             }
    
             ...
        }
    }
    

    So hope this helps.

    Btw. If someone knows the official webpage of the Bean Validation API, please tell... Thanx.