Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude one item from Enum when using zod.nativeEnum

I am new to zod schema validator. I have a use case, where I want exclude one item from the list of enum.

I have a colour enum.

enum Color {
  Red = 'red',
  Green = 'green',
  Blue = 'blue',
}

I want exclude blue from when I creating the validation schema.

I am using zod.nativeEnum ti validate an enum. How do I exclude one item from zod.nativeEnum

I have checked like the following. But that was wrong approch


const schema = z.object({
  color: z.nativeEnum(Color).not(Color.Red),
});
like image 548
Sufail Kalathil Avatar asked Sep 01 '25 10:09

Sufail Kalathil


1 Answers

You can use a mix of union & literal:

z.union([z.literal(Color.Green), z.literal(Color.Blue)])

Link to example: https://codesandbox.io/s/pedantic-beaver-rfefvh

like image 148
Chilly Avatar answered Sep 04 '25 01:09

Chilly