Results 1 to 2 of 2

Thread: How can I access the validator configured through the Spring MVC namespace?

  1. #1
    Join Date
    Dec 2010
    Posts
    2

    Default How can I access the validator configured through the Spring MVC namespace?

    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.

  2. #2
    Join Date
    Dec 2010
    Posts
    2

    Default

    Quote Originally Posted by DLG2209TVX View Post
    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");
        	}
        }
    }

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •