Skip to content

array ​

An array whose every item is validated with one schema.

Signature ​

ts
function array<T>(item: Schema<T>, msg?: Message): Schema<T[]>

Parameters ​

ParameterTypeDescription
itemSchema<T>The schema for each item
msgMessageCustom message. Replaces the default messages for all errors of this schema

Error codes ​

CodeWhenDefault message
requiredThe value is emptyRequired
arrayNot an arrayMust be an array

You can change the texts: see Messages & i18n.

Notes ​

  • An empty array [] is valid. To require at least one item: pipe(array(...), minLength(1)).
  • Item errors have a path with an index: items.2.title.
  • All items are validated, not only until the first error.
  • The array length is checked with minLength, maxLength and length.

Examples ​

Order items ​

ts
const Order = object({
  items: pipe(
    array(object({ id: number(), qty: pipe(number(), integer(), min(1)) })),
    minLength(1, 'The cart is empty'),
  ),
});

validate(Order, { items: [{ id: 1, qty: 0 }] }).errors; // { 'items.0.qty': 'Must be at least 1' }

Tags ​

ts
const tags = optional(array(pipe(string(), trim(), toLowerCase())), () => []);

See also ​