Skip to content

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 ​

ParameterTypeDescription
fieldsstring[]Names of sibling fields
schemaSchema<T>The value schema when it is provided

Error codes ​

CodeWhenDefault message
requiredThe value is empty and the field is requiredRequired

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' }

See also ​