Yup validator makes it easy to validate arrays of data in JavaScript and TypeScript applications. You can define arrays containing strings, numbers, objects, enums, or even nested structures. Each element in the array can have its own validation rules, such as required fields, minimum or maximum values, uniqueness, or custom tests.
This article explains how to define array schemas with .array()
and .of()
, validate data against them using .validate()
, and handle errors effectively. You will also learn how to work with arrays of strings, numbers, objects, enums, and mixed types. Additionally, it covers advanced scenarios like nested arrays, unique constraints, and displaying all validation errors at once using abortEarly: false
.
By the end of this guide, you will understand how to build robust and reliable forms, APIs, and data-driven applications using Yup arrays. Step by step, you’ll learn both the basics and the advanced techniques needed for type-safe, consistent, and fully validated data structures.
Defining a Yup Array
Yup lets you define arrays by combining .array()
with .of()
. The .array()
method declares that the field must be an array, and .of(schema)
ensures that each element inside the array follows the specified rules. This makes it easy to validate lists of values such as numbers, strings, or even objects.
const numbersSchema = yup.array().of(yup.number().positive());
Explanation:
yup.array()
→ starts an array schema..of(yup.number().positive())
→ each element must be a number greater than zero.- This definition means
[1, 5, 10]
will pass, but[1, -3, 4]
will fail because-3
is not positive.
Validating a Yup Array
Once you’ve defined an array schema, the next step is to validate actual input data against it. Yup provides the .validate()
method, which checks the data and either returns the validated value or throws detailed error messages.
const numbersSchema = yup.array().of(yup.number().positive());
try {
const result = await numbersSchema.validate([3, 7, -2]);
console.log("Valid data:", result);
} catch (err) {
if (err instanceof yup.ValidationError) {
console.log("Validation failed:", err.errors);
}
}
Explanation:
.validate([3, 7, -2])
→ checks each number in the array.- The first two values are fine, but
-2
breaks the.positive()
rule. - Yup throws a
ValidationError
, and the error message is logged in the console. - If you pass
[3, 7, 12]
, the schema succeeds, and the validated array is returned.
Different Scenarios in Yup Arrays
Yup arrays can be customized for a wide variety of use cases. From simple lists of strings to complex nested objects, you can combine array methods with other Yup schemas to cover almost any validation scenario.
Yup Array of Strings
// Can be empty
yup.array().of(yup.string()).required("Array of strings is required")
// Cannot be empty
yup.array().of(yup.string()).min(1, "Array cannot be empty")
In the above example, the first yup schema allows an empty array and is required, while the second enforces at least one element, ensuring the array is not empty.
Yup Array of Numbers
yup.array().of(yup.number().positive().integer())
In this example, the schema ensures the field is an array and every element is a positive integer.
Yup Array of Objects
const productsSchema = yup.array()
.of(
yup.object({
name: yup.string().required(),
price: yup.number().positive().required()
})
)
.required("Products array is required")
.min(1, "At least one product is required")
.test("unique", "Products must be unique", (arr) =>
arr ? new Set(arr.map(p => p.name)).size === arr.length : true
);
Explanation:
This Yup array of objects schema ensures that:
- The array is required and cannot be empty (at least one object).
- Each object follows its own schema validation rules with
name
andprice
fields. - The array contains unique objects based on the
name
property. - Works seamlessly in TypeScript with type-safe validation for structured data.
Yup Array of Enums
yup.array().of(
yup.string().oneOf(["admin", "editor", "viewer"])
)
Each element in the array must match one of the predefined enum values.
Yup Array of Specific Type
yup.array().of(yup.number())
This ensures the array contains only numbers, enforcing consistent type validation across all elements.
Error Handling in Yup Arrays
When validating arrays, Yup can return one or multiple error messages depending on the configuration. By default, Yup stops at the first error (abortEarly: true
).
If you want to see all validation issues at once, you can set abortEarly: false
. This is especially useful when you want to display multiple form errors together.
const tagsSchema = yup.array()
.of(yup.string().min(3, "Each tag must be at least 3 characters"))
.min(2, "At least two tags are required")
.max(5, "You can add up to 5 tags");
try {
await tagsSchema.validate(["js", "a"], { abortEarly: false });
} catch (err) {
if (err instanceof yup.ValidationError) {
console.log("Validation errors:");
err.errors.forEach((message) => console.log("-", message));
}
}
Explanation:
.min(2)
requires at least two tags..of(yup.string().min(3))
ensures each tag is at least 3 characters long.- Input
["js", "a"]
fails two checks:- The second tag
"a"
is too short. - Only two tags are provided, but one fails the length rule.
- The second tag
- Because
abortEarly: false
is used, Yup reports all validation errors in a single run instead of stopping at the first failure.
Conclusion
Yup arrays give you fine-grained control over validating lists of data, whether you’re working with simple strings, numbers, or complex nested objects. By combining .array()
with .of()
, you can define precise rules for each element, while methods like .min()
, .max()
, .required()
, and .ensure()
let you enforce structure and constraints at the array level.
With proper error handling—especially using abortEarly: false
—you can provide clear, user-friendly feedback that highlights all validation issues at once. This makes Yup arrays an essential tool for building reliable forms, APIs, and data-driven applications where consistency and correctness are critical.
Mastering Yup arrays not only improves validation in your current projects but also lays the foundation for exploring more advanced Yup features like nested schemas and custom validations.