ealush / vest

Vest ✅ Declarative validations framework

Home Page:https://vestjs.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for enums

alveshelio opened this issue · comments

Hi,

First of all, a big thank you for this package. I've recently discovered it and decided to give it a try and I really like the simplicity compared to others out there.

I'd like to know if you have any plans to support enums.

Let's say, a select can only be one of the values of an enum, instead of use .isString() we could use isInEnum(MyEnum). Unless this is already supported by the library, I wasn't able to find the doc regarding enums.

Thank you

Hey @alveshelio, thanks for reaching out.

The short answer to your question is yes, what you want done can be achieved pretty easily with inside, it allows you to check that a value is within an array.

enforce("hello").inside(["hello", "world"]);

The thing is that a typescript enum is not an array, but it transpiles down to an object, so it's not useful just like that. You need to get either the keys or the values:

enum Fruits {
  APPLE = "apple",
  BANANA = "banana",
  CANTELOPE = "cantelope"
}

// ...

// If you need the enum by key:
test('fruit', 'fruit is a key of fruits enum', () => {
  // data.fruit is a key of ["APPLE", "BANANA", "CANTELOPE"]
  enforce(data.fruit).inside(Object.keys(Fruits));
});

// If you need the enum by value:
test('fruit', 'fruit is a value of fruits enum', () => {
  // data.fruit is a value of ["apple", "banana", "cantelope"]
  enforce(data.fruit).inside(Object.values(Fruits));
});

Maybe it's a good idea to add two new matchers keyOf and valueOf`, but until then, these two examples should work for you.

Hi @ealush,

Thank you very much for getting back. I think inside() might be enough.

Great example, would be nice to have it in the docs re: handling enum/select ! @ealush

Thanks @MentalGear, added to the docs will be automatically published with the next patch to vest.

Thank you for keeping an eye out for things like this.