How to validate is either string or array of strings with Yup, React and JavaScript?

Sometimes, we want to validate is either string or array of strings with Yup, React and JavaScript.

In this article, we’ll look at how to validate is either string or array of strings with Yup, React and JavaScript.

How to validate is either string or array of strings with Yup, React and JavaScript?

To validate is either string or array of strings with Yup, React and JavaScript, we can use the mixed and when methods.

For instance, we write:

import React from "react";
import * as yup from "yup";
import { Formik, Form, Field } from "formik";

const validationSchema = yup.object().shape({
  email: yup
    .mixed()
    .when("isArray", {
      is: Array.isArray,
      then: yup.array().of(yup.string()),
      otherwise: yup.string()
    })
    .required()
});

export default function App() {
  return (
    <Formik
      initialValues={{ email: "" }}
      validationSchema={validationSchema}
      onSubmit={(values) => {
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field name="email" />
          {errors.email && touched.email ? <div>{errors.email}</div> : null}
          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  );
}

to add a form with the Formik and Form components.

We set the validationSchema prop to an object returned by object and shape to let us validate the value object.

We set the email property of the schema object to an object returned by mixed and when to add conditional validation.

And we set is to Array.isArray to check if email is an array.

If it’s true, then we validate that is an array of strings by setting then to yup.array().of(yup.string()).

Otherwise, we set the otherwise property to yup.string to validate that email is a string.

Conclusion

To validate is either string or array of strings with Yup, React and JavaScript, we can use the mixed and when methods.