object
An object with the given fields. Validates each field with its schema and collects errors of all fields at once.
Signature
ts
function object<S extends Record<string, Schema>>(shape: S, options?: ObjectOptions): Schema<ObjectOut<S>>
interface ObjectOptions {
unknown?: 'strip' | 'strict' | 'passthrough';
message?: Message;
}Parameters
| Parameter | Type | Description |
|---|---|---|
shape | Record<string, Schema> | Object fields and their schemas |
options.unknown | 'strip' | 'strict' | 'passthrough' | What to do with keys not in shape. Default: strip |
options.message | Message | Custom message if the value is empty or not an object |
Unknown keys
| Mode | What happens to keys not in shape |
|---|---|
strip (default) | Removed from data. Protects from mass assignment: isAdmin: true from a request won't reach the database |
strict | An unknownKey error for each unknown key |
passthrough | Kept in data as is |
Error codes
| Code | When | Default message |
|---|---|---|
required | The value is empty | Required |
object | Not an object (or an array) | Must be an object |
unknownKey | An unknown key in strict mode | Unknown field |
You can change the texts: see Messages & i18n.
Notes
optionalfields without a value are not added todataat all.- Only own properties are read, never the prototype. A
__proto__key in the input is safe. - Errors of nested objects have a path:
address.city.
Examples
Nested objects
ts
const Order = object({
customer: object({
name: string(),
phone: string(),
}),
address: object({
city: string(),
street: string(),
}),
});
validate(Order, { customer: { name: 'Ann' }, address: {} }).errors;
// { 'customer.phone': 'Required', 'address.city': 'Required', 'address.street': 'Required' }Strict API
ts
const UpdateUser = object({ name: optional(string()) }, { unknown: 'strict' });
validate(UpdateUser, { name: 'Ann', isAdmin: true }).errors; // { isAdmin: 'Unknown field' }See also
- array
- optional — optional fields
- sameAs — comparing fields
- TypeScript — object type from a schema