Validating an object or array of similarly-shaped objects with Yup

Bjorn Krolsavatar

Bjorn Krols

Published on
23 January 2022

It is a common requirement for a single API endpoint to accept both a single object and an array of similarly shaped objects.

In this brief article you will learn how to implement such validation logic with Yup.

TLDR

import * as yup from "yup";

const CarSchema = yup.object().shape({
  brand: yup.string().required(),
  color: yup.string().required(),
  weight: yup.number().required().positive().integer(),
});

const ArrayOfCarsSchema = yup.array().of(CarSchema);

const CarOrArrayOfCarsSchema = yup.lazy((value) => {
  if (Array.isArray(value)) {
    return ArrayOfCarsSchema;
  }
  return CarSchema;
});

CarOrArrayOfCarsSchema.validateSync({ brand: "Honda", weight: -1 });

Guide

Install yup:

npm install yup

Start with a schema that validates the shape of a single object:

import * as yup from "yup";

const CarSchema = yup.object().shape({
  brand: yup.string().required(),
  color: yup.string().required(),
  weight: yup.number().required().positive().integer(),
});

Derive a schema that validates an array of those objects:

const ArrayOfCarsSchema = yup.array().of(CarSchema);

Create a final schema that picks the right schema based on the value that's being validated:

const CarOrArrayOfCarsSchema = yup.lazy((value) => {
  if (Array.isArray(value)) {
    return ArrayOfCarsSchema;
  }
  return CarSchema;
});

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this