Search code examples
zod

Can I validate an exact value with zod?


Validating a string can be done with a regex. That's easy.

const myString = z.string().regex(/A string/);

But what about other data types?

I guess the following could work for number, but it doesn't seem idiomatic.

const myNumber = z.number().gte(7).lte(7);

Is there a better way?


Solution

  • You can use Zod Literals to match exact values. Inferred types will also be exactly the value specified rather than number.

    For example:

    const myNumber = z.literal(7);