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
| 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 (
?).
Example
ts
const Order = object({
delivery: oneOf(['pickup', 'courier']),
// pickup point is required for everything except courier delivery
pickupPoint: requiredUnless({ delivery: 'courier' }, string()),
});