requiredWith
The field is required if at least one of the listed fields is filled. Like required_with in Laravel.
Signature
ts
function requiredWith<T>(fields: string[], schema: Schema<T>): Schema<T | undefined>Parameters
| Parameter | Type | Description |
|---|---|---|
fields | string[] | Names of sibling fields |
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
Any value except undefined, null and '' counts as filled — see Empty values.
Example
ts
const ChangePassword = object({
password: optional(pipe(string(), minLength(8))),
passwordConfirm: requiredWith(['password'], pipe(string(), sameAs('password'))),
});
validate(ChangePassword, {}).valid; // true — nothing to change
validate(ChangePassword, { password: 'secret123' }).errors; // { passwordConfirm: 'Required' }