Search code examples
typescriptdatedatetimevalidationzod

Zod coercion to date custom error message


I have a zod schema that needs to validate a datetime from html input. Here's how it looks:

const appointmentSchema = z.object({
  appointmentTime: z.coerce.date()
})

The problem is when I interact with the input and it is invalid, like the image below. Zod returns me the following error message: Invalid date.

enter image description here

I want to customize this message but nothing seems to work, I've already tried the following:

...z.coerce.date({
invalid_type_error: 'Custom invalid date message. Doesn't work...'
})...

Solution

  • As pointed by @adsy in the comments. This is a known issue https://github.com/colinhacks/zod/issues/1526

    The workaround is overriding the errorMap:

    dateOfBirth: z
            .date({
              errorMap: (issue, { defaultError }) => ({
                message: issue.code === "invalid_date" ? "That's not a date!" : defaultError,
              }),
            })