Issue
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) {
...
}
Solution
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);
Answered By - Biju Kunjummen
Answer Checked By - Mildred Charles (JavaFixing Admin)