Yup Enum: Using oneof Method Validation


When validating user input, sometimes you need to ensure a field only accepts one value from a fixed list — like a user role ('admin' | 'editor' | 'viewer') or a payment status ('pending' | 'completed' | 'failed'). That’s where Yup enum-like validation becomes essential. In this guide, you’ll learn how to use Yup to validate against specific sets of values, handle edge cases, and make your schema strict yet flexible.

Yup doesn’t have a direct .enum() method like Zod, but you can achieve the same effect using .oneOf(). For example:

Try It Yourself: Code Example

import * as Yup from 'yup';

Yup.string().oneOf(['admin', 'editor', 'viewer']).required()

This ensures that only the defined roles are accepted. If a user sends 'guest', validation fails immediately.

Edge Cases in Yup Enum

Let’s look at some edge cases where Yup’s enum-style validation becomes tricky:

  • Case sensitivity: .oneOf() checks exact matches, so 'Admin' fails if the list only includes 'admin'. To handle this, you can normalize input using .transform(value => value.toLowerCase()).
  • Optional enums: If a field can be null or undefined, chain .nullable() or .notRequired().
  • Mixed types: Yup enforces type safety. A number 1 won’t match '1' unless explicitly cast with .transform(String).
  • Dynamic enums: When allowed values depend on runtime data, you can generate .oneOf(dynamicList) dynamically.

Summary

Yup’s .oneOf() acts as the perfect substitute for enum validation in schema design. It helps enforce consistency, reduce invalid states, and simplify form logic. By handling edge cases like optional fields and case sensitivity, you can build more resilient validation layers that align closely with real-world data rules. Whether it’s user roles, statuses, or categories, Yup enum validation ensures your app always receives trusted, predefined inputs.

You can explore more advanced techniques in our guide on powerful JS schema validation to strengthen your overall Yup setup.

Author

Sharukhan is the founder of Tecktol. He has worked as a software engineer specializing in full-stack web development.