Spring – Using both JSR-303 and Traditional Bean Validation

bean-validationspringspring-mvc

Is it possible to use both JSR-303 bean validation and traditional validation (a single validator class for the type) in Spring? If so, what configuration is required to set this up?

I have tried the instructions on the reference.

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(new DualEntryValidator());
}

@RequestMapping(value="/dualEntry.htm", method = RequestMethod.POST)
public ModelAndView handlePost(@Valid DualEntryForm form, BindingResult result) {
    ModelAndView modelAndView = new ModelAndView("dualEntry", getCommonModel());

    if (!result.hasErrors()){
        //do logic
        return modelAndView;

    }else {
        modelAndView.addObject("dualEntryForm", form);
        return modelAndView;
    }
}

I can get this to use my custom Validator or the JSR-303 validation, but not both. If I have the initBinder present as in the example it uses the custom Validator. If I remove it the JSR-303 bean validation is used. How can I use both?

Best Answer

I've done that following the instructions here:

http://blog.jteam.nl/2009/08/04/bean-validation-integrating-jsr-303-with-spring/

See the "Enjoy both worlds" section. Shortly, you explicitly run a JSR303 validation from a Spring validator, "joining" the results of JSR303 validations based on annotations and your custom validation logic.

Related Topic