`z.literal` message not customizable
When I try to customize the message of a z.literal, I get the following output:
try {
z.literal('correct', { message: 'must match' }).parse('incorrect');
} catch (err) {
console.log('err: ', err);
}
// err: ZodError: [
// {
// "received": "incorrect",
// "code": "invalid_literal",
// "expected": "correct",
// "path": [],
// "message": "Invalid literal value, expected \"correct\""
// }
// ]
when I would expect to get
// err: ZodError: [
// {
// "received": "incorrect",
// "code": "invalid_literal",
// "expected": "correct",
// "path": [],
// "message": "must match"
// }
// ]
This landed in a recent version of Zod, you'll need to upgrade to v3.23.0+
I'm getting that behavior on 3.25.6. In using https://zod-playground.vercel.app/, if I have z.literal('test', { message: 'wrong' }) and give undefined, the message shows as expected (see screenshot below). However, if I have the wrong value the message goes back to the default one (second screenshot).
Note this doesn't happen with other Zod types:
@colinhacks I think this is still an issue in v3.25.6 (see above)
also v3.23.8
This issue is still happening. Please re-open.
up
Hi @craig-jennings! I'm Dosu and I’m helping the zod team.
You're correct—custom error messages for z.literal aren't applied for incorrect values in Zod v3.25.6. This happens because the implementation doesn't attach the message param to invalid_literal issues, so the default error message is always used for literal mismatches, even though other types like z.string do respect custom messages for their errors. You can see this in the code for ZodLiteral and the error map logic here.
As a workaround, you can globally override error messages using a custom error map with z.setErrorMap. For example:
import { z } from "zod";
z.setErrorMap((issue, ctx) => {
if (issue.code === z.ZodIssueCode.invalid_literal) {
return { message: "must match" };
}
return { message: ctx.defaultError };
});
This will apply your custom message to all literal mismatches. More details are in the docs.
If you want more granular control or per-schema messages, Zod v4 introduces a new error customization API that lets you use a function to generate error messages based on the issue, which resolves this inconsistency see discussion. If possible, consider upgrading to v4 for more flexible error handling.
Let me know if this helps or if you need a more specific workaround! If your question is answered, feel free to close the issue.
To reply, just mention @dosu.
How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other
I think it can be closed