0

Conditional validation of bean in a list field.

I have a little problem with bean validation. I would like to do a conditional validation, but the validated class have as a field a list of bean which must be also validated, and some of these bean's fields must be conditionally validated.

Here is my code :

public class ParentBean {

    @Valid
    private List<ChildBean> childBeans;

}

public class ChildBean {

    boolean flag;

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

    String cannotBeNull();
}

I could do a loop on the child beans and validate each child separitively but the path in the errors would be wrong

Addittionnaly, I could use a solution like this one : Cross field validation with Hibernate Validator (JSR 303) but it seems to mess up with the path associated to the error...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Teocali
  • 2,725
  • 2
  • 23
  • 39

1 Answers1

0

I Find a workaround : I first validate the parent Bean then I validate each ChildBean separatively and for each error found, I add it to the set of errors of the ParentBean, updating the path in the process

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 conditional 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());
        }
    }
}

I didn't provide the code for the method validateChildBean as it is quite trivial, but don't hesitate to ask it in comments, I will be happy to oblige :)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Teocali
  • 2,725
  • 2
  • 23
  • 39