Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Valid (javax.validation.Valid) is not recursive for the type of list

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.

like image 685
Anil Bhaskar Avatar asked Jun 13 '19 11:06

Anil Bhaskar


People also ask

What is the difference between @valid and validated?

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.

What is @valid in javax?

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 }

What happens when @valid fails?

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 .

Where is @valid annotation is used to validate a form?

In controller class: The @Valid annotation applies validation rules on the provided object. The BindingResult interface contains the result of validation.


1 Answers

Have you tried it like this:

class Parent {
    @NotNull // javax.validation.constraints.NotNull
    private String name;

    @Valid
    List<Child> children;
}
like image 171
user2665115 Avatar answered Sep 19 '22 10:09

user2665115