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
| Parameter | Type | Description |
|---|---|---|
condition | Condition | Sibling fields and their values: { delivery: 'courier' }; several values — an array: { delivery: ['courier', 'post'] }. Or a function |
schema | Schema<T> | The value schema when it is provided |
msg | Message | Custom message |
Error codes
| Code | When | Default message |
|---|---|---|
prohibited | The condition holds but a value is provided | Must 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 }