Skip to content

requiredWith ​

列出的字段中至少有一个已填写时,该字段为必填。类似 Laravel 的 required_with。

签名 ​

ts
function requiredWith<T>(fields: string[], schema: Schema<T>): Schema<T | undefined>

参数 ​

参数类型说明
fieldsstring[]同级字段的名称
schemaSchema<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' }

另请参阅 ​