Skip to content

oneOf ​

One of the listed values — like an enum or Laravel's in: rule.

Signature ​

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

Parameters ​

ParameterTypeDescription
values`readonly (stringnumber
msgMessageCustom message. Replaces the default messages for all errors of this schema

Error codes ​

CodeWhenDefault message
requiredThe value is emptyRequired
oneOfThe value is not in the listMust be one of: {options}

You can change the texts: see Messages & i18n.

Notes ​

  • The result type is a union of the values: oneOf(['admin', 'user']) → 'admin' | 'user'.
  • The {options} parameter is the values joined with commas.
  • Strict comparison: oneOf([1, 2]) rejects the string '1'. For query strings use preprocess(Number, oneOf([1, 2])).

Example ​

User role ​

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' }

See also ​