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

Viewed 5242

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.

5 Answers

Have you tried it like this:

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

    @Valid
    List<Child> children;
}

Try adding,

class Parent {
    @NotNull 
    private String name;

    @NotNull 
    @Valid
    List<Child> children;
}

If you want to validate the child then you have to mention @Valid to the attribute itself

Parent Class

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

  @NotNull // Not necessary if it's okay for children to be null
  @Valid // javax.validation.Valid
  privateList<Child> children;
}

Child class

class Child {
  @NotNull
  private String name;
}

With Bean Validation 2.0 and Hibernate Validator 6.x, it is recommended to use:

class Parent {
    @NotNull 
    private String name;

    List<@Valid Child> children;
}

We support @Valid and constraints in container elements.

However, what the others suggested should work.

annotate in Parent your list with @Valid and add @NotEmpty or @NotBlank or @NotNull to Child. Spring will validate it just fine.

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

    @Valid
    List<Child> children;
}

class Child {
  @NotNull
  private String name;
}
Related