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
| 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 |
Error codes
| Code | When | Default message |
|---|---|---|
required | The value is empty and the field is required | Required |
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 todata, 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()),
});