admin管理员组文章数量:1420135
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 badges1 Answer
Reset to default 4You 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' ] }
}
本文标签: javascriptZod get nested object inside array field errorsStack Overflow
版权声明:本文标题:javascript - Zod get nested object inside array field errors - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745323503a2653485.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论