requiredUnless
条件不满足时字段为必填。类似 Laravel 的 required_unless。
签名
ts
function requiredUnless<T>(condition: Condition, schema: Schema<T>): Schema<T | undefined>
type Condition = Record<string, unknown> | ((info: { parent: unknown; root: unknown }) => boolean)参数
| 参数 | 类型 | 说明 |
|---|---|---|
condition | Condition | 同级字段及其值:{ delivery: 'courier' };多个值用数组:{ delivery: ['courier', 'post'] }。也可以是函数 |
schema | Schema<T> | 值存在时使用的 Schema |
错误代码
| 代码 | 触发条件 | 默认信息 |
|---|---|---|
required | 值为空且该字段为必填 | Required |
可以修改这些文本:见 错误信息与国际化。
注意事项
- 条件中的字段在该字段所在的同一对象中查找。嵌套字段用点表示:
{ 'company.type': 'org' }。如需访问全部数据,请使用函数 —— 它接收{ parent, root }。 - 当字段不是必填时,它与
optional相同:空值不会进入data,传入的值会按 Schema 校验。 - 在 TypeScript 类型中,该字段变为可选(
?)。
示例
ts
const Order = object({
delivery: oneOf(['pickup', 'courier']),
// pickup point is required for everything except courier delivery
pickupPoint: requiredUnless({ delivery: 'courier' }, string()),
});