Yup validate is either String or Array of strings

david_adler picture david_adler · Jul 2, 2019 · Viewed 8.1k times · Source

I would like to validate that a field is either a string or an array of strings

Here is a minimal failing example which happens to use formik but actually I am doing server side validation using yup.

  {
    email: yup
      .mixed()
      .oneOf([yup.array().of(yup.string()), yup.string()])
      .nullable()
  }

Answer

Tymek picture Tymek · Jul 3, 2019
{
  email: yup.mixed()
    .when('isArray', {
      is: Array.isArray,
      then: yup.array().of(yup.string()),
      otherwise: yup.string(),
    })
}

But a set of checkboxes can produce an array, and text input would not. Are you searching for a solution to validate emails divided by separator?