最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Zod get nested object inside array field errors - Stack Overflow

programmeradmin2浏览0评论

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 ?

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 ?

Share Improve this question asked Aug 2, 2023 at 8:25 Mehdi FarajiMehdi Faraji 3,89410 gold badges46 silver badges96 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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' ] }
}
发布评论

评论列表(0)

  1. 暂无评论