Skip to content

oneOf ​

列出的值之一 —— 类似 enum 或 Laravel 的 in: 规则。

签名 ​

ts
function oneOf<const T extends readonly (string | number | boolean)[]>(values: T, msg?: Message): Schema<T[number]>

参数 ​

参数类型说明
values`readonly (stringnumber
msgMessage自定义信息。替换该 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' }

另请参阅 ​