【问题标题】:@Valid (javax.validation.Valid) is not recursive for the type of list@Valid (javax.validation.Valid) 对于列表类型不是递归的
【发布时间】:2019-06-13 11:38:07
【问题描述】:

控制器:

@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;
}

这会为 Parent.name 触发 @NotNull,但不会检查 Child.name。 如何让它触发。我试过List&lt;@Valid Child&gt; children; 也用@Valid 注释来注释子类,不起作用。请帮忙。

parent = { "name": null } 失败。名称不能为空。

child = { "name": null } 有效。

【问题讨论】:

  • 抱歉,问题出在其他问题上。我没有正确检查错误。

标签: java spring-boot spring-mvc hibernate-validator javax.validation


【解决方案1】:

你有没有这样尝试过:

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

    @Valid
    List<Child> children;
}

【讨论】:

  • 是的,这也不行。看起来这验证了列表,而不是类型。
  • 嗯,这实际上应该像这里描述的那样工作:beanvalidation.org/1.0/spec/… 我猜第二个答案。
【解决方案2】:

尝试添加,

class Parent {
    @NotNull 
    private String name;

    @NotNull 
    @Valid
    List<Child> children;
}

【讨论】:

    【解决方案3】:

    如果你想验证孩子,那么你必须在属性本身中提到@Valid

    父类

    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;
    }
    

    儿童班

    class Child {
      @NotNull
      private String name;
    }
    

    【讨论】:

      【解决方案4】:

      使用 Bean Validation 2.0 和 Hibernate Validator 6.x,建议使用:

      class Parent {
          @NotNull 
          private String name;
      
          List<@Valid Child> children;
      }
      

      我们支持@Valid 和容器元素中的约束。

      但是,其他人的建议应该可行。

      【讨论】:

        【解决方案5】:

        annotateParent 你的列表中加上@Valid 并将@NotEmpty@NotBlank@NotNull 添加到Child。 Spring 会很好地验证它。

        class Parent {
            @NotNull // javax.validation.constraints.NotNull
            private String name;
        
            @Valid
            List<Child> children;
        }
        
        class Child {
          @NotNull
          private String name;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-14
          • 2012-11-19
          • 1970-01-01
          • 2013-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-12
          相关资源
          最近更新 更多