colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
32.88k stars 1.14k forks source link

Using the key of string enum using nativeEnum? #3617

Open hls-app opened 2 months ago

hls-app commented 2 months ago

So I have been using this Country enum and wondering if we can validate the keys instead of the value?

https://gist.github.com/evolkmann/740d24889c509c08484a8ff72af5dd64

Currently, the nativeEnum validates the value and could not find an option to make it validate the key instead.

hls-app commented 2 months ago

Currently using this as I cannot flip the enum just for Zod

z.string().length(2).regex(/^[A-Z]{2}$/, 'Invalid country code').nullable()
nabil-rady commented 2 months ago

This how I did it

z.enum(Object.keys(Enum) as [keyof typeof Enum, ...(keyof typeof Enum[]])

Let me know if you have a better idea than this.