Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
      .mixed()
      .oneOf([yup.array().of(yup.string()), yup.string()])
      .nullable()
  }
like image 365
david_adler Avatar asked Jul 02 '19 15:07

david_adler


4 Answers

{
  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?

like image 135
Tymek Avatar answered Oct 24 '22 00:10

Tymek


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()))
}
like image 26
david_adler Avatar answered Oct 23 '22 23:10

david_adler


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.")
         .nullable()
like image 6
Ajay Kumar Avatar answered Oct 23 '22 23:10

Ajay Kumar


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()
        .of(PathnameValidator.required())
        .required()
      : PathnameValidator.required();
  }),
like image 2
Sebastien Lorber Avatar answered Oct 23 '22 23:10

Sebastien Lorber