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

javascript - Formatting zod schema validation errors - Stack Overflow

programmeradmin6浏览0评论

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 0
Add a ment  | 

1 Answer 1

Reset to default 4

You 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.

发布评论

评论列表(0)

  1. 暂无评论