当前位置: 首页 > 知识库问答 >
问题:

如何在列表字段中对bean进行条件验证

陈飞语
2023-03-14

列表字段中bean的条件验证。

我对bean验证有一个小问题。我想做一个条件验证,但是被验证的类有一个必须被验证的bean列表作为字段,这些bean的一些字段必须被条件验证。这里有一个示例代码:

public class ParentBean {

    @Valid
    private List<ChildBean> childBeans;

}

public class ChildBean {

    boolean flag;

    @NotNull(condition="flag")
    String mustNotBeNullFlagTrue;

    String cannotBeNull();
}

我可以在子bean上做一个循环,并分别验证每个子bean,但错误中的路径是错误的

另外,我可以使用这样的解决方案:使用Hibernate Validator(JSR 303)进行跨域验证,但它似乎弄乱了与错误相关的路径。。。

共有1个答案

司徒胤
2023-03-14

我找到了一个解决方法:首先验证父Bean,然后分别验证每个子Bean,对于发现的每个错误,我将其添加到父Bean的错误集中,并在过程中更新路径

public Errors validateParentBean(ParentBean parentBean) {
    //We create the errors list for the parent bean. 
    DefaultMessageContext msgContext = new DefaultMessageContext();
    private MessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver();
    MessageContextErrors parentBeanErrors = new MessageContextErrors(msgContext, "parentBean", null, null, messageCodesResolver, null);

    List<ChildBean> childBeanList = parentBean.getChildBeans();


    //for each childBean
    for (int childBeanIndex = 0; childBeanIndex < childBeanList.size(); childBeanIndex++) {
        ChildBean ChildBean = childBeanList.get(childBeanIndex);
        //we validate the bean. In this method we do the conditionnal validation itself
        MessageContextErrors childBeanErrors = validateChildBean(ChildBean);
        //for each error
        for (int errorIndex = 0; errorIndex < childBeanErrors.getFieldErrors().size(); errorIndex++) {
            //we "pull" it up, to the parentBean, updating the path in the way
            FieldError fieldError = (FieldError) childBeanErrors.getFieldErrors().get(errorIndex);
            parentBeanErrors.rejectValue("childBeans[" + childBeanIndex + "]."+fieldError.getField(), fieldError.getCode());
        }
    }
}

我没有提供方法validateChildBean的代码,因为它非常琐碎,但请不要犹豫,在评论中询问它,我很乐意:)

 类似资料:
  • 我正在使用Springboot和Thyemleaf,试图用javax验证我的表单数据。验证。约束注释。 在我的模板中,我使用了一个Thyem立夫命令对象,它是我的模型类。在模型中,我有一些经过验证的字段- 这是用于输入文本/标题的超文本标记语言- 以下是提交表单时endpoint的控制器- 在我的模板中,我可以提交表单,如果或为空并且插入了带有消息的新div,将返回字段错误。 我遇到字段列表问题

  • 问题内容: 尝试通过关联获取时,“字段列表”中出现未知列“ userDetails.createdAt”。 无需关联即可正常使用。 我的代码如下: 问题答案: 我认为错误是您在序列化中启用了时间戳,但是数据库中的实际表定义不包含时间戳列。 当您执行user.find时,它只会执行,而只接受您实际拥有的列。但是,当您联接时,联接表的每一列都将被别名,这将创建以下查询: 解决方法是禁用任一userDe

  • 我将MVC3视图模型定义为: 使用FluentValidation(v3.3.1.0)将验证定义为: 账户验证可能被定义为: 我希望列表中的每个帐户按照留档中的描述进行验证。但是,调用不起作用,因为在使用

  • 我想根据数字字段对搜索结果进行排序。在下面的示例代码中,我希望基于'Age'字段进行排序。我从以下答案开始: [如何在Lucene 6中对IntPont或LongPoint字段进行排序 [在Lucene中根据数字字段对搜索结果进行排序 我在搜索函数中将sortfield.type.score更改为sortfield.type.long。但我得到: 意外的docvalues为字段“年龄”键入NONE

  • 本文向大家介绍如何在Python中对字符串列表进行排序?,包括了如何在Python中对字符串列表进行排序?的使用技巧和注意事项,需要的朋友参考一下 要对列表进行排序,即对列表本身进行排序并更改列表本身的顺序,可以在字符串列表中使用。例如, 如果要保持原始列表不变,而要一个新的排序元素列表,则可以使用sorted(list)。例如,