Skip to content

requiredUnless ​

The field is required unless the condition holds. Like required_unless in Laravel.

Signature ​

ts
function requiredUnless<T>(condition: Condition, schema: Schema<T>): Schema<T | undefined>

type Condition = Record<string, unknown> | ((info: { parent: unknown; root: unknown }) => boolean)

Parameters ​

ParameterTypeDescription
conditionConditionSibling fields and their values: { delivery: 'courier' }; several values — an array: { delivery: ['courier', 'post'] }. Or a function
schemaSchema<T>The value schema when it is provided

Error codes ​

CodeWhenDefault message
requiredThe value is empty and the field is requiredRequired

You can change the texts: see Messages & i18n.

Notes ​

  • Condition fields are looked up in the same object as the field itself. Nested ones — with a dot: { 'company.type': 'org' }. To reach all the data use a function — it receives { parent, root }.
  • When the field isn't required it works like optional: an empty value doesn't go to data, a provided one is validated by the schema.
  • In the TypeScript type the field becomes optional (?).

Example ​

ts
const Order = object({
  delivery: oneOf(['pickup', 'courier']),
  // pickup point is required for everything except courier delivery
  pickupPoint: requiredUnless({ delivery: 'courier' }, string()),
});

See also ​