RepoPilot

How do I define a custom validator in zod?

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

Question

How do I define a custom validator in zod?

RepoPilot

Great! I found the answer. Based on the code, Zod provides the refine() method to define custom validators:

Custom Validators with .refine()

You can use the .refine() method on any Zod schema to add custom validation logic [packages/zod/src/v3/types.ts:L318-L357]. Here's how it works:

Basic Syntax:

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

Key features:

  1. Check function: The first argument is a function that receives the validated value and should return a truthy value if validation passes, or falsy if it fails.

  2. Error message: The second argument is optional and can be:

    • A string message
    • An object with custom error properties
    • A function that computes error properties based on the value being validated
  3. Async support: The check function can return a Promise for async validation [packages/zod/src/v3/types.ts:L337-L345].

  4. Type narrowing: You can use a type predicate as the check function to narrow the output type.

The method returns a ZodEffects schema wrapping your original schema with the refinement applied. When validation fails, it adds an issue with code ZodIssueCode.custom.

For more fine-grained control over error reporting, you might also look into superRefine() which gives you access to the validation context for adding multiple issues.

Did this answer what you came for?

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.