Skip to content

prohibitedIf ​

The field must be empty if the condition holds, otherwise it's optional. Like prohibited_if in Laravel.

Signature ​

ts
function prohibitedIf<T>(condition: Condition, schema: Schema<T>, msg?: Message): 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
msgMessageCustom message

Error codes ​

CodeWhenDefault message
prohibitedThe condition holds but a value is providedMust be empty

You can change the texts: see Messages & i18n.

Notes ​

Protects from data that must not come together: a price for a free item, a company tax ID for an individual.

Example ​

ts
const Product = object({
  type: oneOf(['free', 'paid']),
  price: prohibitedIf({ type: 'free' }, coerce.number()),
});

validate(Product, { type: 'free', price: '10' }).errors; // { price: 'Must be empty' }
validate(Product, { type: 'paid', price: '10' }).data;   // { type: 'paid', price: 10 }

See also ​