requiredWith
列出的字段中至少有一个已填写时,该字段为必填。类似 Laravel 的 required_with。
签名
ts
function requiredWith<T>(fields: string[], schema: Schema<T>): Schema<T | undefined>参数
| 参数 | 类型 | 说明 |
|---|---|---|
fields | string[] | 同级字段的名称 |
schema | Schema<T> | 值存在时使用的 Schema |
错误代码
| 代码 | 触发条件 | 默认信息 |
|---|---|---|
required | 值为空且该字段为必填 | Required |
可以修改这些文本:见 错误信息与国际化。
注意事项
除 undefined、null 和 '' 之外的任何值都视为已填写 —— 见 空值。
示例
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' }