RepoPilot

How do I define a custom validator in zod?

About colinhacks/zod · 2 messages · last activity 8/1/2026

Question

How do I define a custom validator in zod?

RepoPilot

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:

  1. check - A function that receives the parsed value and returns a truthy value if valid, falsy if invalid
  2. message (optional) - An error message, which can be:
    • A string: "Custom error message"
    • A CustomErrorParams object
    • A function that generates error params based on the value

How It Works

When you call refine, it wraps your validation function in a refinement that:

  • Executes your check function against the parsed value
  • If the check returns falsy, it calls ctx.addIssue() with code ZodIssueCode.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/zod

Public Q&A. Generated by RepoPilot from the actual source of colinhacks/zod. AI answers can be incomplete or stale — verify before relying on them.