NodeJS Zod获取数组字段内的嵌套对象错误

isr3a4wc  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(138)

我用zod定义了sizes数组的模式:

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

字符串
我把这个有效载荷

"sizes" : [ {} ]


但函数e.flatten()不会像price , off_price , sell_quantity那样显示嵌套对象字段错误,并给出以下错误消息

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


我如何告诉zod显示对象字段的所有错误消息?

bd1hkmkf

bd1hkmkf1#

可以使用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]);
}

字符串
日志:

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' ] }
}

相关问题