TAGS :Viewed: 2 - Published at: a few seconds ago

[ @InitBinder restricting to single validator ]

In my controller, when I set a validator to the webdatabinder:

@InitBinder
private void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}

My controller only applies that validator and ignore other fields' validation:

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public void processRecord(@Valid @RequestBody Record record, Errors errors) {
    //code
}

The field validation ignored are annotation based:

@NotNull
@Size(min = 2, max = 60, message="firstName must be between 2 and 60 characters long.")
private String firstName;

Is there a way to add the custom validator and still apply the default annotation based validation?

Answer 1


Adding a custom validator does indeed override the default ones.

There is a need to inject a basic validator on top of the custom one:

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.replaceValidators(validator, basicValidator);
    }

The @Autowired basic validator being declared as follow:

    @Bean
    public Validator basicValidator() {
        return new LocalValidatorFactoryBean();
    }