Yup validate is either String or Array of strings

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
      .oneOf([yup.array().of(yup.string()), yup.string()])

  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?

oneOf only works with literal values. Lazy allows you to provide a schema dynamically as shown below

  email: yup.lazy(val => (Array.isArray(val) ? yup.array().of(yup.string()) : yup.string()))

This YUP simple validation work for my case when Form contains multi-select field and keeping this field as mandatory and at least one option is required to select.

 selectOptions: array()
         .min(1, "You can't leave this blank.")
         .required("You can't leave this blank.")

David Adler’s solution is the working one for me.

Here’s a TS-based variant:

  from: Yup.lazy<string | string[]>(from => {
    return Array.isArray(from)
      ? Yup.array()
      : PathnameValidator.required();

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   D3 javascript Difference between foreach and each

Similar Posts