Search code examples
javascriptnode.jstypescriptvalidationzod

Zod get nested object inside array field errors


I defined the schema for the sizes array like this with zod :

z.object({
    sizes: z.array(
        z.object({
          price: z.string().nonempty(),
          off_price: z.string().nonempty(),
          sell_quantity: z.string().nonempty(),
        })
      )
      .nonempty(),
  })
  .strict();

And I send this payload

 "sizes" : [ {} ]

But the function e.flatten() won't show the nested object field errors like price , off_price , sell_quantity and gives me this error message

"message": "{"formErrors":[],"fieldErrors":{"sizes":["Required","Required","Required"]}}",

How can I tell zod to show all error messages of the object fields ?


Solution

  • You can use Error formatting

    import { z } from 'zod';
    
    const schema = z
      .object({
        sizes: z
          .array(
            z.object({
              price: z.string(),
              off_price: z.string(),
              sell_quantity: z.string(),
            }),
          )
          .nonempty(),
      })
      .strict();
    
    const result = schema.safeParse({ sizes: [{}] });
    if (!result.success) {
      console.log('result.error.issues: ', result.error.issues);
      console.log('result.error.format(): ', result.error.format().sizes?.[0]);
    }
    

    Logs:

    result.error.issues:  [
      {
        code: 'invalid_type',
        expected: 'string',
        received: 'undefined',
        path: [ 'sizes', 0, 'price' ],
        message: 'Required'
      },
      {
        code: 'invalid_type',
        expected: 'string',
        received: 'undefined',
        path: [ 'sizes', 0, 'off_price' ],
        message: 'Required'
      },
      {
        code: 'invalid_type',
        expected: 'string',
        received: 'undefined',
        path: [ 'sizes', 0, 'sell_quantity' ],
        message: 'Required'
      }
    ]
    result.error.format():  {
      _errors: [],
      price: { _errors: [ 'Required' ] },
      off_price: { _errors: [ 'Required' ] },
      sell_quantity: { _errors: [ 'Required' ] }
    }