36

I'm using yup to create validations for my data , how can i handle enums?

this is a sample of my validations - I'm using object.shape method of the yup:

export const deleteCityValidation = yup.object().shape({
  id: yup.string()
});

looking for a way to validate an input field that should only have a value from a set of enums any help is appreciated .

is it possible to use yup.arrays to validate enums ?

PayamB.
  • 706
  • 1
  • 9
  • 28
  • 17
    Looking at the docs something like: `yup.mixed().oneOf(Object.values(YOUR_ENUM))` could work. – r3dst0rm Jan 21 '20 at 08:31
  • @r3dst0rm thanks for the comment i think that might fix the problem but i should test it , I'm really sorry to ask such a stupid question but whats that ```< keyof typeof > ``` thing called? i mean the whole thing inside these < > – PayamB. Jan 21 '20 at 08:56
  • 2
    An enum is under the hood nothing more than an object, with typeof you let TypeScript infer a type and with keyof we can get all valid indices of that object as a type. Since `mixed` is a generic function which needs a type definition, we put such a type inside those `< >` brackets. – r3dst0rm Jan 21 '20 at 09:05

2 Answers2

33

you can use example like below:

let schema = yup.mixed().oneOf(['jimmy', 42]);

await schema.isValid(42); // => true
await schema.isValid('jimmy'); // => true
await schema.isValid(new Date()); // => false

more info

hbinduni
  • 1,170
  • 17
  • 27
25

The code below works for your example:

  field: yup.mixed<EnumName>().oneOf(Object.values(EnumName))
    .required(),
b0b
  • 346
  • 3
  • 6