【问题标题】:How to do conditional validation of bean in a list field如何在列表字段中对 bean 进行条件验证
【发布时间】:2015-08-21 09:29:01
【问题描述】:

对列表字段中的 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,但错误中的路径是错误的

另外,我可以使用这样的解决方案:Cross field validation with Hibernate Validator (JSR 303),但它似乎与错误相关的路径混淆了......

【问题讨论】:

  • 只需编写一个自定义验证器。

标签: java validation bean-validation


【解决方案1】:

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

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 方法的代码,因为它非常琐碎,但请不要犹豫,在 cmets 中询问,我很乐意效劳:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    相关资源
    最近更新 更多