Type-safe, customizable error message mapping for Zod validation
npm install zod-error-mapType-safe, customizable error message mapping for Zod validation.
``bash`
npm install zod-error-map
`js
import { z } from 'zod'
import { setZodErrorMap } from 'zod-error-map'
setZodErrorMap(z)
const schema = z.object({
email: z.string().email(),
password: z.string().min(8),
})
schema.parse({ email: 'invalid', password: '123' })
// Error: The 'email' must be a valid email address
`
`js
import { z } from 'zod'
import { setZodErrorMap, ErrorCode } from 'zod-error-map'
setZodErrorMap(z, {
defaultError: 'Validation failed',
formatMessages: {
email: (label) => Please enter a valid email for ${label.quoted},${label.bare} needs at least ${issue.minimum} characters
},
builders: {
[ErrorCode.TOO_SMALL]: (issue, label) =>
,`
},
})
`js
import { createErrorMapper } from 'zod-error-map'
const mapper = createErrorMapper({
defaultError: 'Invalid input',
})
const message = mapper.format({
code: 'invalid_type',
path: ['email'],
input: undefined,
expected: 'string',
})
// "The email is required"
`
`js
import { z } from 'zod'
import { createZodErrorMap } from 'zod-error-map'
z.setErrorMap(createZodErrorMap())
`
Sets the global Zod error map using z.config() (Zod v4).
Creates a Zod error map compatible with z.setErrorMap() (Zod v3).
Creates an error mapper instance with custom configuration.
| Option | Type | Description |
|--------|------|-------------|
| defaultError | string | Default error message when no builder matches |builders
| | Record | Custom message builders by error code |formatMessages
| | Record | Custom messages for format validation errors |
- ErrorCode.INVALID_TYPE - Type mismatch or missing required fieldErrorCode.TOO_SMALL
- - Value below minimum length/valueErrorCode.TOO_BIG
- - Value above maximum length/valueErrorCode.INVALID_FORMAT
- - Invalid format (email, uuid, url, etc.)ErrorCode.CUSTOM
- - Custom validation errors
FormatType.EMAIL, FormatType.UUID, FormatType.URL, FormatType.REGEX, FormatType.CUID, FormatType.CUID2, FormatType.ULID, FormatType.IP, FormatType.DATE, FormatType.DATETIME, FormatType.TIME`
MIT