admin管理员组文章数量:1403361
I want to know if there is a way to reformat the schema validation errors object returned by Zod such that the error strings can include the invalid input value provided. For example, instead of just having the error message "Number must be greater than 0.", the following error can be returned with actual value of the number: "Number must be greater than 0, but received: -3".
I want to know if there is a way to reformat the schema validation errors object returned by Zod such that the error strings can include the invalid input value provided. For example, instead of just having the error message "Number must be greater than 0.", the following error can be returned with actual value of the number: "Number must be greater than 0, but received: -3".
Share Improve this question asked Mar 19, 2023 at 19:18 LemourLemour 3233 gold badges4 silver badges11 bronze badges 01 Answer
Reset to default 4You can pass a custom ZodErrorMap to your parse()
call which gives you access both the issue
and a ctx
object containing the data passed to parse()
as well as a default message. You can then specify specific messages for each issue.code
.
sandbox
import { z } from "zod";
const customErrorMap: z.ZodErrorMap = (error, ctx) => {
console.log(ctx);
/*
This is where you override the various error codes
*/
switch (error.code) {
case z.ZodIssueCode.too_small:
return {
message: `Expected a number >= ${error.minimum} but got ${ctx.data}`,
};
default:
// fall back to default message!
return { message: ctx.defaultError };
}
};
z.number().min(0).parse(-3, { errorMap: customErrorMap });
/*
ZodError: [
{
"code": "too_small",
"minimum": 0,
"type": "number",
"inclusive": true,
"exact": false,
"message": "Expected a number >= 0 but got -3",
"path": []
}
]
*/
Error maps can be assigned at various scopes with more specific scopes taking priority over higher level maps. see Error map priority.
本文标签: javascriptFormatting zod schema validation errorsStack Overflow
版权声明:本文标题:javascript - Formatting zod schema validation errors - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744391104a2603982.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论