Controller:
@RequestMapping(...)
public void foo(@Valid Parent p){
}
class Parent {
@NotNull // javax.validation.constraints.NotNull
private String name;
List<Child> children;
}
class Child {
@NotNull
private String name;
}
This triggers @NotNull
for Parent.name but doesn't check for Child.name.
How to make it trigger. I tried List<@Valid Child> children;
also annotate Child class with @Valid
annotation, doesn't work. Please help.
parent = { "name": null }
fails. name can't be null.
child = { "name": null }
works.
Just for simplifying: @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. @Valid annotation on method parameters and fields to tell Spring that we want a method parameter or field to be validated. Hope this helps.
The @Valid annotation is used to mark nested attributes, in particular. This triggers the validation of the nested object. For instance, in our current scenario, we can create a UserAddress object: public class UserAddress { @NotBlank private String countryCode; // standard constructors / setters / getters / toString }
When you use the @Valid annotation for a method argument in the Controller , the validator is invoked automatically and it tries to validate the object, if the object is invalid, it throws MethodArgumentNotValidException .
In controller class: The @Valid annotation applies validation rules on the provided object. The BindingResult interface contains the result of validation.
Have you tried it like this:
class Parent {
@NotNull // javax.validation.constraints.NotNull
private String name;
@Valid
List<Child> children;
}
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