RepoPilot

How do I define a custom validator in zod?

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

Question

How do I define a custom validator in zod?

RepoPilot

I can see from the source that Zod supports custom validation through its refinement method. Based on the code in [packages/zod/src/v3/types.ts:L1035-L1041], there's a _regex method that demonstrates the pattern:

protected _regex(regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage) {
  return this.refinement((data) => regex.test(data), {
    validation,
    code: ZodIssueCode.invalid_string,
    ...errorUtil.errToObj(message),
  });
}

This shows that you can use .refinement() to define custom validators. The refinement accepts:

  1. A validation function that returns a boolean
  2. An options object with error details (code, message, etc.)

However, the repository data I have doesn't include the full API documentation or examples of custom validator usage. To get more complete information about how to define custom validators with different patterns and options, you would want to check the main Zod documentation or look at the full type definitions for the refinement method.

The code also shows various built-in string validators (email, uuid, url, regex, etc.) defined as checks in [packages/zod/src/v3/types.ts:L545-L587], which might serve as useful patterns for understanding how validators are structured.

FOLLOW_UPS:

  • What's the difference between refinement and superRefine?
  • How do custom validators interact with error handling?
  • Can I create reusable custom validator functions?

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.