提问人:Guan-Bo Yang 提问时间:9/30/2023 更新时间:9/30/2023 访问量:100
使用 Zod 检索更正后的数据和错误消息
Retrieve both corrected data and error message with Zod
问:
我正在使用 Zod 进行架构验证,并且正在尝试在验证失败时检索更正后的数据和错误消息。让我用一个简化的例子来说明。
给定此架构:
const testSchema = z.number().min(0).array();
const test = testSchema.safeParse([1, -1]);
我可以使用以下命令检索错误消息:
console.log(test.error.flatten());
// Expected output:
// {
// formErrors: [],
// fieldErrors: { '1': [ 'Number must be greater than or equal to 0' ] }
// }
但是,当我尝试捕获错误并提供更正的数据时:
const testSchema = z.number().min(0).catch(0).array();
const test = testSchema.safeParse([1, -1]);
错误将消失,结果如下:
console.log(test.data); // Expected output: [1, 0]
如何调整架构或输入分析,以便在验证失败时同时获取更正后的数据和关联的错误消息?
我尝试了管道函数来实现这一点。但是,这似乎与我想要实现的结果无关。
我希望同时获得更正后的数据(如)和相关的错误消息(例如)。[1, 0]
{ '1': [ 'Number must be greater than or equal to 0' ] }
答: 暂无答案
上一个: 解析(抓取)时代替数字
评论