Manually call Spring Annotation Validation Manually call Spring Annotation Validation spring spring

Manually call Spring Annotation Validation


Going a step further than Jaiwo99 in his answer:

// org.springframework.validation.SmartValidator - implemented by//     LocalValidatorFactoryBean, which is funny as it is not a FactoryBean per se (just saying)@AutowiredSmartValidator validator;public String saveAccount(@ModelAttribute Account account, BindingResult result) {    // ... custom logic    validator.validate(account, result, Account.Step1.class);    if (result.hasErrors()) {        // ... on binding or validation errors    } else {        // ... on no errors    }    return "";}

And the mandatory link to SmartValidator JavaDoc if you are interested.


Here is a code sample from JSR 303 spec

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();Driver driver = new Driver();driver.setAge(16);Car porsche = new Car();driver.setCar(porsche);Set<ConstraintViolation<Driver>> violations = validator.validate( driver );

So yes, you can just get a validator instance from the validator factory and run the validation yourself, then check to see if there are violations or not. You can see in the javadoc for Validator that it will also accept an array of groups to validate against.

Obviously this uses JSR-303 validation directly instead of going through Spring validation, but I believe spring validation annotations will use JSR-303 if it's found in the classpath


If you have everything correctly configured, you can do this:

@AutowiredValidator validator;

Then you can use it to validate you object.