reactjsreact-hook-formzod

Zod custom validation for non empty value


I have a simple form to create a new shop for customers. My issue is this, I have a select option with a value of 'nill' and I want zod to show an error message if this option is selected.

This is my zod schema

categoryId: z.string().min(1, 'Shop category is required!')

So how do I add a custom validation that also returns the message 'Shop category is required!' if the selected value is nill. I am new to zod and know of refine but I don't know how to implement it


Solution

  • You need to use the .refine() method to add a custom validation.

    const schema = z.object({
      categoryId: z
        .string()
        .min(1, {message: 'Shop category is required!'})
        .refine((value) => value !== 'nill', {
          message: 'Shop category is required!',
        }),
    });
    

    Or,

    But in this case, you may not a refine(); you can achieve the same result by,

    const schema = z.object({
      categoryId: z
        .string()
        .nonempty({message: 'Shop category is required!'})
        .refine((value) => value !== 'nill', {
          message: 'Shop category is required!',
        }),
    });
    

    The .refine() method in Zod is typically used for more complex, custom validation logic that goes beyond the basic constraints like string length or presence. It's perfect for scenarios like- Validating one field based on another field's value.