z.date() not respecting custom error messages
Glazy opened this issue · comments
This problem was described first in #1526, but that issue was auto-closed as stale despite not being resolved.
I'd expected that providing the invalid_type_error
option to z.date()
would override the "Invalid Date"
error but it doesn't.
For now, I have worked around this with the following code (credit @shinnoki) from the aforementioned issue:
dateOfBirth: z
.date({
errorMap: (issue, { defaultError }) => ({
message: issue.code === "invalid_date" ? "That's not a date!" : defaultError,
}),
})
Ultimately this is behaving as intended. This is an unfortunate and confusing side effect of the fact that Zod makes a distinction between invalid_type
and invalid_date
issues. There is a certain logic to this, since new Date("blah")
is still an instanceof Date
but it's counter-intuitive.
Closing this because this won't be changed in Zod 3, as it would be a breaking change. In Zod 4, invalid dates will fail validation against z.date()
as you expect.
You could always just usage message
to overwrite all errors (but this might not be what you want).
z.date({
message: "Invalid date",
});
Thanks for the explainer @colinhacks. I can see the logic too; especially since an invalid date is still instanceof Date
as you mentioned.
I think overriding all of the messages might actually work in my case, I'll check tomorrow.
Glad to know this won't even be something we have to think about in Zod v4 🔥