Skip to main content

Error Maps

Error maps allow you to customize error messages based on the validation issue type and context.

Basic Error Map

An error map is a function that receives an issue and returns a custom message:

Error Map Return Values

Error maps can return:
  • { message: string } - Custom error message
  • string - Shorthand for { message: string }
  • undefined or null - Fall back to default message

Contextual Error Maps

Apply error maps to specific parse operations:

Refinements with Error Maps

Schema-Bound Error Maps

Bind error maps directly to schemas:

Bound vs Contextual Precedence

Schema-bound error maps take precedence over contextual ones:

Global Error Configuration

Set a global custom error map using z.config():
Global error maps affect all validations in your application. Use with caution and consider schema-bound or contextual error maps for more targeted customization.

Error Map Issue Types

Invalid Type Issues

Size Constraint Issues

Invalid Format Issues

Custom Issues with Params

Advanced Error Map Patterns

Path-Aware Error Messages

Unrecognized Keys

Invalid Union

Combining Error Messages

Hard-Coded Message with Error Map

Error and Message Conflict

You cannot use both message and error options together. The message option is a shorthand that takes precedence.

Empty String Messages

You can explicitly set empty error messages:

Best Practices

  1. Return undefined for defaults - Let Zod generate standard messages when appropriate
  2. Use params for context - Pass metadata through params for dynamic messages
  3. Prefer schema-bound for reusable schemas - Bind error maps to schemas you’ll reuse
  4. Use contextual for one-off customization - Apply custom error maps at parse time for specific cases
  5. Avoid global error maps in libraries - They affect all Zod usage in the application
  6. Consider internationalization - Error maps are perfect for translating messages