
Originally Posted by
DLG2209TVX
http://static.springsource.org/sprin...vc-configuring
If I use this:
<mvc:annotation-driven validator="globalValidator"/>
Or if I put a JSR-303 validator on the classpath and use this:
<mvc:annotation-driven />
How can I then access that validator inside my controller? Basically, I want to extend that validator, and call it after it has been bound to the model so I can run additional custom validation.
It wasn't very obvious, but you can get the validator off the WebDataBinder during initialization and then wrap it in your custom validator. In this implementation you have to call the JSR-303 validator instance first, and then do any of your custom validation.
Controller:
Code:
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
Validator validator = binder.getValidator();
binder.setValidator(new CustomValidator(validator));
}
...do other controller stuff here...
}
CustomValidator:
Code:
public class CustomValidator implements Validator {
private Validator validator;
public CustomValidator(Validator validator) {
this.validator = validator;
}
@SuppressWarnings("rawtypes")
public boolean supports(Class clazz) {
return MyModel.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
validator.validate(target, errors);
MyModel myModel = (MyModel) target;
if (myModel.someBooleanField()) {
errors.rejectValue("mySpringFormError", "some.configured.property.message");
}
}
}