I have the following code in a Spring controller:
@Autowired
private javax.validation.Validator validator;
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitForm(CustomForm form) {
Set<ConstraintViolation<CustomForm>> errors = validator.validate(form);
...
}
Is it possible to map errors
to Spring's BindingResult
object without manually going through all the errors and adding them to the BindingResult
? Something like this:
// NOTE: this is imaginary code
BindingResult bindingResult = BindingResult.fromConstraintViolations(errors);
I know it is possible to annotate the CustomForm
parameter with @Valid
and let Spring inject BindingResult
as another method's parameter, but it's not an option in my case.
// I know this is possible, but doesn't work for me
public String submitForm(@Valid CustomForm form, BindingResult bindingResult) {
...
}
The real use of @Valid annotation is in the class (bean) that you are validating with JSR 303 validator and its primary use is to validate the object graph. Meaning one bean can have other bean references with @Valid annotation to trigger validation recursively.
Bean Validation. JSR-303 bean validation is an specification whose objective is to standardize the validation of Java beans through annotations. The objective of the JSR-303 standard is to use annotations directly in a Java bean class.
You can perform validation with Errors/BindingResult object. Add Errors argument to your controller method and customize the error message when errors found. Below is the sample example, errors. hasErrors() returns true when validation is failed.
A simpler approach could be to use Spring's abstraction org.springframework.validation.Validator
instead, you can get hold of a validator by having this bean in the context:
<bean id="jsr303Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
@Autowired @Qualifier("jsr303Validator") Validator validator;
With this abstraction in place, you can use the validator this way, passing in your bindingResult:
validator.validate(obj, bindingResult);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With