Skip to content

requiredIf ​

The field is required if the condition holds, otherwise it's optional. Like required_if in Laravel.

Signature ​

ts
function requiredIf<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 (?).

Examples ​

Address only for delivery ​

ts
const Order = object({
  delivery: oneOf(['pickup', 'courier', 'post']),
  address: requiredIf({ delivery: ['courier', 'post'] }, pipe(string(), minLength(5))),
});

validate(Order, { delivery: 'courier' }).errors; // { address: 'Required' }
validate(Order, { delivery: 'pickup' }).data;    // { delivery: 'pickup' }

A condition function ​

ts
const Company = object({
  type: oneOf(['person', 'org']),
  kpp: requiredIf(({ parent }) => parent.type === 'org', string()),
});

See also ​