How do I define a custom validator in zod?
How do I define a custom validator in zod?
About colinhacks/zod · 2 messages · last activity 8/1/2026
Based on the source code, zod provides the refine method to define custom validators. Here's how it works:
The refine Method
The refine method is defined in [packages/zod/src/v3/types.ts:L318-L357] and allows you to add custom validation logic to any schema.
Basic Usage
refine(
check: (arg: Output) => unknown,
message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)
): ZodEffects<this, Output, Input>
The method accepts:
check- A function that receives the parsed value and returns a truthy value if valid, falsy if invalidmessage(optional) - An error message, which can be:- A string:
"Custom error message" - A
CustomErrorParamsobject - A function that generates error params based on the value
- A string:
How It Works
When you call refine, it wraps your validation function in a refinement that:
- Executes your
checkfunction against the parsed value - If the check returns falsy, it calls
ctx.addIssue()with codeZodIssueCode.custom[packages/zod/src/v3/types.ts:L337-L346] - Supports both synchronous and asynchronous checks (via Promise detection)
Example from the Code
The implementation shows that the error message can be dynamically computed [packages/zod/src/v3/types.ts:L327-L334]:
const getIssueProperties = (val: Output) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
This means you can provide a function to generate contextual error messages based on the value being validated.
FOLLOW_UPS:
- How do I use async validators in zod?
- What's the difference between refine and superRefine?
- Can I add multiple custom validators to one schema?
Want to ask your own question?
Open chat for colinhacks/zodPublic Q&A. Generated by RepoPilot from the actual source of colinhacks/zod. AI answers can be incomplete or stale — verify before relying on them.