oneOf
列出的值之一 —— 类似 enum 或 Laravel 的 in: 规则。
签名
ts
function oneOf<const T extends readonly (string | number | boolean)[]>(values: T, msg?: Message): Schema<T[number]>参数
| 参数 | 类型 | 说明 |
|---|---|---|
values | `readonly (string | number |
msg | Message | 自定义信息。替换该 Schema 所有错误的默认信息 |
错误代码
| 代码 | 触发条件 | 默认信息 |
|---|---|---|
required | 值为空 | Required |
oneOf | 值不在列表中 | Must be one of: {options} |
可以修改这些文本:见 错误信息与国际化。
注意事项
- 结果类型是这些值的联合类型:
oneOf(['admin', 'user'])→'admin' | 'user'。 - 信息中的
{options}参数是用逗号连接的值。 - 使用严格比较:
oneOf([1, 2])不接受字符串'1'。对于 query 请使用preprocess(Number, oneOf([1, 2]))。
示例
用户角色
ts
const ROLES = ['admin', 'editor', 'user'] as const;
const User = object({
role: optional(oneOf(ROLES), 'user'),
});
validate(User, { role: 'root' }).errors; // { role: 'Must be one of: admin, editor, user' }另请参阅
- literal:一个特定的值
- preprocess