Skip to content

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 ​

ParameterTypeDescription
shapeRecord<string, Schema>Object fields and their schemas
options.unknown'strip' | 'strict' | 'passthrough'What to do with keys not in shape. Default: strip
options.messageMessageCustom message if the value is empty or not an object

Unknown keys ​

ModeWhat 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
strictAn unknownKey error for each unknown key
passthroughKept in data as is

Error codes ​

CodeWhenDefault message
requiredThe value is emptyRequired
objectNot an object (or an array)Must be an object
unknownKeyAn unknown key in strict modeUnknown field

You can change the texts: see Messages & i18n.

Notes ​

  • optional fields without a value are not added to data at 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 ​