Home > Enterprise >  Make multiple Formik-fields required with Yup if any of them have a value
Make multiple Formik-fields required with Yup if any of them have a value

Time:12-29

I have a Formik-form which is validated with Yup. My problem is that all three fields, let's call them Field1, Field2, and Field3 (all are Strings), are optional by default, but all of them are required if any of them are filled out.

What would my validationSchema look like to make this work

I already have a starting-point with two other fields where if one is filled out the other is not required anymore, but one of them must be filled out at all times, it looks like this:

field4: Yup.string()
            .ensure()
            .when('field5', {
                is: '',
                then: Yup.string().required('Please fill out Field4 or Field5'),
            }),
field5: Yup.string()
            .ensure()
            .when('field4', {
                is: '',
                then: Yup.string().required(''),
            }),

CodePudding user response:

In yup you can check depending on other values using when as you did with field4 and field5. And you can actually listen to more than one field at the same time.

You have to be careful with cyclic dependencies

There is some solution using the param noSortEdges but there is not much documentation around it. You can find a test of it working here.

So a possible solution would be:

const schema = yup.object().shape(
  {
    field1: yup.string().when(["field2", "field3"], {
      is: (a, b) => a !== undefined || b !== undefined,
      then: yup.string().required("Please fill out Field1, Field2 or Field3")
    }),
    field2: yup.string().when(["field1", "field3"], {
      is: (a, b) => a !== undefined || b !== undefined,
      then: yup.string().required("Please fill out Field1, Field2 or Field3")
    }),
    field3: yup.string().when(["field1", "field2"], {
      is: (a, b) => a !== undefined || b !== undefined,
      then: yup.string().required("Please fill out Field1, Field2 or Field3")
    })
  },
  [["field1", "field2"], ["field1", "field3"], ["field2", "field3"]]
);

  • Related