Martin Asenov opened SPR-14615 and commented
Class with RestController annotation
Method with RequestMapping annotation, method is POST
Map@Valid
and @RequestBody
CustomDto has @NotNull
on one of its fields.
The input passes even though a CustomDto entry is not valid (null value on the @NotNull
field)
When I try to change the Map with a single CustomDto, it is validated correctly, but when a map, it is not.
Affects: 4.2.5
Issue Links:
- #16519 Bean Validation invocation API for use with individual values and constraints
- #18007 @Validated
support on Iterables (and implementors)
- #16917 Add support for validating a collection of objects
1 votes, 3 watchers
Comment From: spring-projects-issues
Juergen Hoeller commented
There is no standard support for validating top-level Map
or Collection
objects in case of Bean Validation. We may consider introducing custom support for it.
Comment From: spring-projects-issues
Martin Asenov commented
@Juergen
Hoeller ok, but how do I workaround this for now? Any suggestions?
Comment From: spring-projects-issues
Juergen Hoeller commented
You could inject an @Autowired Validator
into your controller class and programmatically call Validator.validate
on each of your map values.
Comment From: spring-projects-issues
Martin Asenov commented
thanks, I'll give it a try, even though it is not comprehensible to me why such basic functionality is not supported.
Comment From: spring-projects-issues
Juergen Hoeller commented
Agreed, it is unintuitive that this doesn't work. This is partially due to the JavaBean nature of both the Bean Validation spec and Spring's data binding, where collections and maps are only defined to be nested within top-level objects.
Simply speaking, we're just passing the given object to javax.validation.Validator.validate
, and that method never finds any constraint validation on collection or map objects. If Hibernate Validator doesn't consider support for this directly, we can only manually iterate the collection values and adapt the constraint violation metadata accordingly, even if the won't be able to strictly adhere to the Bean Validation API contract then (e.g. in terms of property path traversal and invalid value handling). We can consider that for 5.0 where several Bean Validation related enhancements are waiting already.
Comment From: spring-projects-issues
Martin Asenov commented
I coulnd't get the suggested approach to work too.
@Autowired
private Validator validator;
@RequestMapping(value = "/", method = RequestMethod.POST)
public void postMethod(@RequestBody Map<String, CustomDto> rules, Errors errors) {
rules.values().forEach(value -> {validator.validate(value, errors)});
}
stiill doesn't detect the missing @NotNull
field. Am I missing something?
Thanks
Comment From: rstoyanchev
This is now supported with Bean Validation and the built-in Spring web method validation #30645.