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

本文标签: javascriptFormatting zod schema validation errorsStack Overflow