Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSR-303 validation errors to Spring's BindingResult

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) {
    ...
}
like image 249
Anton Moiseev Avatar asked Feb 15 '13 10:02

Anton Moiseev


People also ask

What does the @valid as part of JSR 303 mean?

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.

What is JSR 303 Bean Validation?

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.

How do I customize default error message from Spring @valid validation?

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.


1 Answers

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);
like image 106
Biju Kunjummen Avatar answered Sep 28 '22 01:09

Biju Kunjummen