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
| Parameter | Type | Description |
|---|---|---|
values | `readonly (string | number |
msg | Message | Custom message. Replaces the default messages for all errors of this schema |
Error codes
| Code | When | Default message |
|---|---|---|
required | The value is empty | Required |
oneOf | The value is not in the list | Must 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 usepreprocess(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
- literal — one specific value
- preprocess