Search code examples
reactjstypescriptzod

How to validate a string literal type using zod


I have this Type

export type PaymentType = 'CHECK' | 'DIRECT DEPOSIT' | 'MONEY ORDER';

I want to validate this literal string type in zod. Currently, I have is as a string, but that wrong is not a string. I don't know what to put.

const schema = z.object({
    paymentType: z.string() // I want to validate this field
});

So far, I have tried enums, strings, and objects. I cannot find the right answer.


Solution

  • I commented that this might be a duplicate since the core of the question could be solved with z.literal, but it is a bit different. Just to illustrate what you can do:

    import { z } from 'zod';
    const PaymentTypeSchema = z.union([
      z.literal('CHECK'),
      z.literal('DIRECT DEPOSIT'),
      z.literal('MONEY ORDER'),
    ]);
    type PaymentType = z.infer<typeof PaymentTypeSchema>;
    
    const schema = z.object({
      paymentType: PaymentTypeSchema,
    });
    

    A simpler approach than this is to use the z.enum helper which removes some of the boilerplate:

    const PaymentTypeSchema = z.enum(["CHECK", "DIRECT DEPOSIT", "MONEY ORDER"]);
    const schema = z.object({
      paymentType: PaymentTypeSchema,
    });
    

    Alternatively, you can make PaymentType into an enum and use z.nativeEnum to parse the values like:

    enum PaymentType {
      Check = 'CHECK',
      DirectDeposit = 'DIRECT DEPOSIT',
      MoneyOrder = 'MONEY ORDER'
    }
    
    const PaymentTypeSchema = z.nativeEnum(PaymentType);
    const schema = z.object({
      paymentType: PaymentTypeSchema,
    });