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

5

8

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.

Peggie answered 13/6, 2019 at 11:38 Comment(1)
Sorry, problem was something else. I wasn't checking the errors right.Peggie
L
8

Have you tried it like this:

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

    @Valid
    List<Child> children;
}
Leathers answered 13/6, 2019 at 11:44 Comment(2)
Yes, this doesn't work as well. Looks this validates the list, not it's type.Peggie
Well this should actually work as described here: beanvalidation.org/1.0/spec/… And I guess the other answers second that.Leathers
M
3

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;
}
Musky answered 13/6, 2019 at 12:13 Comment(0)
P
2

Try adding,

class Parent {
    @NotNull 
    private String name;

    @NotNull 
    @Valid
    List<Child> children;
}
Phonemics answered 13/6, 2019 at 12:7 Comment(0)
S
1

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.

Shushubert answered 13/6, 2019 at 15:45 Comment(0)
M
0

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;
}
Meier answered 13/6, 2019 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.