RepoPilot

How do I define a custom validator in zod?

About colinhacks/zod · 2 messages · last activity 7/5/2026

Question

How do I define a custom validator in zod?

RepoPilot

Based on the Zod codebase, you can define a custom validator using the refine() method.

The refine() method allows you to add custom validation logic to any schema [packages/zod/src/v3/types.ts:L318-L357]. Here's how it works:

Basic syntax:

schema.refine(
  check: (arg: Output) => unknown,
  message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)
)

How it works:

  1. The check function — You pass a function that receives the parsed value and returns a truthy/falsy result
  2. The message — You can provide:
    • A simple string message
    • A function that returns custom error properties based on the value
    • CustomErrorParams object directly

Error handling:

When validation fails (the check returns falsy), Zod creates an issue with code: ZodIssueCode.custom and your custom error message [packages/zod/src/v3/types.ts:L338-L345].

Async support:

The refine() method also supports async validators — if your check function returns a Promise, Zod will handle it asynchronously and wait for the result before determining if validation passes [packages/zod/src/v3/types.ts:L348-L357].

You can also use _refinement() internally for lower-level custom validation logic [packages/zod/src/v3/types.ts:L335].

FOLLOW_UPS:

  • What string validation formats does Zod support built-in?
  • Can you chain multiple validators together?
  • How do I create async custom validators with Zod?

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.