ArticleZip > Yup Validate Is Either String Or Array Of Strings

Yup Validate Is Either String Or Array Of Strings

When working with data validation in programming, understanding how to check whether a value is a string or an array of strings can be really handy. Fortunately, the `Yup` validation library in JavaScript provides a straightforward way to accomplish this task.

To validate whether a value in Yup is either a string or an array of strings, you can make use of the `mixed` and `array` schema types in combination with the `test` method.

Firstly, define a schema using the `mixed` method. This allows you to check for a single string value. For example:

Javascript

const schema = yup
  .mixed()
  .test('is-string-or-array', 'Value must be a string or an array of strings', value => {
    if (typeof value === 'string') {
      return true;
    } else {
      return yup
        .array()
        .of(yup.string())
        .validate(value)
        .then(() => true)
        .catch(() => false);
    }
  });

In the above code snippet, we define a schema that checks whether a value is either a string or an array of strings using the `test` method. If the value is a string, the validation returns `true`. If it's an array, the validation checks if all elements are strings using the `array` schema type along with `yup.string()`.

You can now use this schema to validate values in your application:

Javascript

schema.validate('hello').then(result => {
  console.log(result); // true
});

schema.validate(['hello', 'world']).then(result => {
  console.log(result); // true
});

schema.validate(['hello', 123]).catch(error => {
  console.error(error.message); // Value must be a string or an array of strings
});

The code above demonstrates how to use the schema we defined earlier to validate both single string values and arrays of strings. If the validation fails, an error message is thrown indicating that the value must be a string or an array of strings. This can be helpful in ensuring data integrity in your applications.

By leveraging the flexibility of Yup's schema types and the `test` method, you can easily implement custom validations to handle various data scenarios in your projects. Whether it's validating strings, arrays, or complex data structures, Yup provides a robust set of tools to make your validation logic efficient and effective. So next time you need to validate whether a value is a string or an array of strings, remember Yup's got your back!

×