array
An array whose every item is validated with one schema.
Signature
ts
function array<T>(item: Schema<T>, msg?: Message): Schema<T[]>Parameters
| Parameter | Type | Description |
|---|---|---|
item | Schema<T> | The schema for each item |
msg | Message | Custom message. Replaces the default messages for all errors of this schema |
Error codes
| Code | When | Default message |
|---|---|---|
required | The value is empty | Required |
array | Not an array | Must 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,maxLengthandlength.
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())), () => []);