Skip to content

requiredIf ​

满足条件时字段为必填,否则为选填。类似 Laravel 的 required_if。

签名 ​

ts
function requiredIf<T>(condition: Condition, schema: Schema<T>): Schema<T | undefined>

type Condition = Record<string, unknown> | ((info: { parent: unknown; root: unknown }) => boolean)

参数 ​

参数类型说明
conditionCondition同级字段及其值:{ delivery: 'courier' };多个值用数组:{ delivery: ['courier', 'post'] }。也可以是函数
schemaSchema<T>值存在时使用的 Schema

错误代码 ​

代码触发条件默认信息
required值为空且该字段为必填Required

可以修改这些文本:见 错误信息与国际化。

注意事项 ​

  • 条件中的字段在该字段所在的同一对象中查找。嵌套字段用点表示:{ 'company.type': 'org' }。如需访问全部数据,请使用函数 —— 它接收 { parent, root }。
  • 当字段不是必填时,它与 optional 相同:空值不会进入 data,传入的值会按 Schema 校验。
  • 在 TypeScript 类型中,该字段变为可选(?)。

示例 ​

仅在配送时需要地址 ​

ts
const Order = object({
  delivery: oneOf(['pickup', 'courier', 'post']),
  address: requiredIf({ delivery: ['courier', 'post'] }, pipe(string(), minLength(5))),
});

validate(Order, { delivery: 'courier' }).errors; // { address: 'Required' }
validate(Order, { delivery: 'pickup' }).data;    // { delivery: 'pickup' }

条件函数 ​

ts
const Company = object({
  type: oneOf(['person', 'org']),
  kpp: requiredIf(({ parent }) => parent.type === 'org', string()),
});

另请参阅 ​