'Yup validation for nested form elements in formik

I have a nested Formik form which has checkbox in every new set of form fields added. I am trying to add validation in Yup to achieve:

  1. Atleast one checkbox to be selected among all the sets. enter image description here
  2. Not throw error for other checkboxes if one is selected. enter image description here

Right now, it throws error for other checkboxes if a particular checkbox is selected. Anyone who can guide me on how to prevent this would be really helpful.

Link to the code I have tried so far: https://codesandbox.io/s/formik-nested-form-mx15kt



Solution 1:[1]

The issue is solved using yup .test. As I explained in the comment. Also we need to remove oneOf([true], ...) as the checkbox can be false now. Here is the working example

The Yup schema:

const NestedSchema = Yup.object().shape({
dropdown1: Yup.string().required("Select dropdown 1"),
groupedelements1: Yup.array().of(
  Yup.object().shape({
    textinput: Yup.string().required("Enter text"),
    groupedelements2: Yup.array().of(
      Yup.object().shape({
        dropdown2: Yup.string().required("Select dropdown 2"),
        checkboxinput: Yup.boolean().test(
          "customValidation",
          "Checkboxes",
          function (val) {
            var { parent, from } = this;
            // console.log(from); //e.g. from[1].value

            console.log(from[1].value.groupedelements2);

            console.log(
              from[1].value.groupedelements2.map(
                (data) => data.checkboxinput
              )
            );

            //Getting checkboxes values from groupedelements2 object
            const checkBoxValues = from[1].value.groupedelements2.map(
              (data) => data.checkboxinput
            );

            var result = false;

            //looping over checkBoxValues array
            for (var i = 0; i < checkBoxValues.length; i++) {
              if (checkBoxValues[i]) {
                result = true;
                break; // if one of the checkbox is true then return true and dont validate other checkboxes
              } else {
                result = false;
              }
            }
            console.log(result);
            return result;
          }
        )
      })
    )
  })
)
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1