Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using both JSR-303 and Traditional Bean Validation?

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?

like image 702
C. Ross Avatar asked Jul 26 '11 19:07

C. Ross


2 Answers

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.

like image 75
eolith Avatar answered Sep 24 '22 08:09

eolith


I realise this is quite old, but I got this to work with minimal disturbance to my code

Change binder.setValidator(new DualEntryValidator());

to

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

With setValidator() you're replacing the JSR-303 validator with your one. With addValidator(), the JSR-303 validator is called and so is yours.

You need to make sure that your validator does not overlap with your JSR-303 @NotNull, @Min, @Max, etc. annotations otherwise you'll get duplicate error messages added.

like image 35
Jim Richards Avatar answered Sep 23 '22 08:09

Jim Richards