javascriptzod

How to customize return message of the object schema?


In following schema:

const mySchema = z.object(
  {
    key1: z.string().nonempty(),
    key2: z.record(z.unknown()).optional(),
    key3: z.string().optional(),
  },
  { error: (iss) => (Array.isArray(iss.input) ? 'custom message' : undefined) }
)
.strict();

When schema is given an array I would like to receive a custom message, and if it is not an array or not an object the standard error message, "expected object, received ...".

I do not understand why but when safe parsing a variable which holds an array the schema returns "expected error, received array" instead the custom message.

Any help would be much appreciated.


Solution

  • I have been using syntax from Zod 4, which does not yet have an official NPM package. I resolved the issue by using a ZodErrorMap (which is used in Zod 3) as follows:

    const { z, ZodIssueCode } = require('zod');
    
    const errorMapMySchma = (issue, ctx) => {
      if (issue.code === ZodIssueCode.invalid_type) {
        if (issue.expected === 'object' && issue.received === 'array') {
          return { message: 'custom message' };
        }
      }
      return { message: ctx.defaultError };
    };
    
    const mySchema = z.object(
      {
        key1: z.string().nonempty(),
        key2: z.record(z.unknown()).optional(),
        key3: z.string().optional(),
      },
      { errorMap: errorMapMySchm }
    )
    .strict();