包详细信息

zod-validation-error

causaly19.7mMIT3.5.3

Wrap zod validation errors in user-friendly readable messages

zod, error, validation

自述文件

zod-validation-error

Wrap zod validation errors in user-friendly readable messages.

Build Status npm version

Features

  • User-friendly readable error messages with extensive configuration options;
  • Preserves original error details accessible via error.details;
  • Provides a custom error map for automatic message formatting;
  • Supports both Zod v3 and v4.

Note: This is the v4 version of zod-validation-error. If you are looking for the zod v3 support, please click here

Installation

npm install zod-validation-error

Requirements

  • Node.js v.18+
  • TypeScript v.4.5+

Quick start

import { z as zod } from 'zod/v4';
import { fromError, createErrorMap } from 'zod-validation-error/v4';

// use custom error map to automatically format messages
// this is optional, but recommended
// without this, zod's native error messages will be used
zod.config({
  customError: createErrorMap({
    includePath: true,
  }),
});

// create zod schema
const zodSchema = zod.object({
  id: zod.int().positive(),
  email: zod.email(),
});

// parse some invalid value
try {
  zodSchema.parse({
    id: 1,
    email: 'coyote@acme', // note: invalid email
  });
} catch (err) {
  const validationError = fromError(err);
  // the error is now readable by the user
  // you may print it to console
  console.log(validationError.toString());
  // or return it as an actual error
  return validationError;
}
<summary>Per-format error customization</summary> For more fine-grained control over the error messages, you may pass the error map as an option to the fromError function. typescript import { z as zod } from 'zod/v4'; import { fromError, createErrorMap } from 'zod-validation-error/v4'; // create zod schema const zodSchema = zod.object({ id: zod.int().positive(), email: zod.email(), }); // parse some invalid value try { zodSchema.parse({ id: 1, email: 'coyote@acme', // note: invalid email }); } catch (err) { // create custom error map // this is optional, but recommended // without this, zod's native error messages will be used // and the error will not be user-friendly const errorMap = createErrorMap({ includePath: false, }); const validationError = fromError(err, { error: errorMap, }); // the error is now readable by the user // you may print it to console console.log(validationError.toString()); // or return it as an actual error return validationError; }

Motivation

Zod errors are difficult to consume for the end-user. This library wraps Zod validation errors in user-friendly readable messages that can be exposed to the outer world, while maintaining the original errors in an array for dev use.

Example

Input (from Zod)

[
  {
    "origin": "number",
    "code": "too_small",
    "minimum": 0,
    "inclusive": false,
    "path": ["id"],
    "message": "Number must be greater than 0 at \"id\""
  },
  {
    "origin": "string",
    "code": "invalid_format",
    "format": "email",
    "pattern": "/^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/",
    "path": ["email"],
    "message": "Invalid email at \"email\""
  }
]

Output

Validation error: Number must be greater than 0 at "id"; Invalid email at "email"

API

ValidationError

Main ValidationError class, extending native JavaScript Error.

Arguments

  • message - string; error message (required)
  • options - ErrorOptions; error options as per JavaScript definition (optional)
    • options.cause - any; can be used to hold the original zod error (optional)

Example 1: construct new ValidationError with message

import { ValidationError } from 'zod-validation-error/v4';

const error = new ValidationError('foobar');
console.log(error instanceof Error); // prints true

Example 2: construct new ValidationError with message and options.cause

import { z as zod } from 'zod/v4';
import { ValidationError } from 'zod-validation-error/v4';

const error = new ValidationError('foobar', {
  cause: new zod.ZodError([
    {
      origin: 'number',
      code: 'too_small',
      minimum: 0,
      inclusive: false,
      path: ['id'],
      message: 'Number must be greater than 0 at "id"',
      input: -1,
    },
  ]),
});

console.log(error.details); // prints issues from zod error

createErrorMap

Creates zod-validation-error's errorMap, which is used to format issues into user-friendly error messages.

Meant to be passed as an option to fromError, fromZodIssue, fromZodError, toValidationError or MessageBuilder.

Note: zod-validation-error's errorMap is an errorMap like all others and thus can also be used directly with zod (see https://zod.dev/error-customization for further details).

Arguments

  • options - Object; formatting options (optional) | Name | Type | Description | | ---- | :----: | ----------- | | includePath | boolean | Indicates whether to include the erroneous property key in the error message (optional, defaults to true) | | displayInvalidFormatDetails | boolean | Indicates whether to display invalid format details (e.g. regexp pattern) in the error message (optional, defaults to false) | | maxAllowedValuesToDisplay | number | Max number of allowed values to display (optional, defaults to 10) | | allowedValuesSeparator | string | Used to concatenate allowed values in the message (optional, defaults to ", ") | | allowedValuesLastSeparator | string \| undefined | Used to concatenate last allowed value in the message (optional, defaults to " or "). Set to undefined to disable last separator. | | wrapAllowedValuesInQuote |boolean | Indicates whether to wrap allowed values in quotes (optional, defaults to true). Note that this only applies to string values. | | maxUnrecognizedKeysToDisplay | number | Max number of unrecognized keys to display in the error message (optional, defaults to 5) | | unrecognizedKeysSeparator | string | Used to concatenate unrecognized keys in the message (optional, defaults to ", ") | | unrecognizedKeysLastSeparator | string \| undefined | Used to concatenate the last unrecognized key in message (optional, defaults to " and "). Set to undefined to disable last separator. | | wrapUnrecognizedKeysInQuote |boolean | Indicates whether to wrap unrecognized keys in quotes (optional, defaults to true). Note that this only applies to string keys. | | issuesInTitleCase |boolean | Indicates whether to convert issues to title case (optional, defaults to true). | | unionSeparator | string | Used to concatenate union-issues in user-friendly message (optional, defaults to " or ") | | issueSeparator | string | Used to concatenate issues in user-friendly message (optional, defaults to ";") | | dateLocalization | boolean \| Intl.LocalesArgument | Indicates whether to localize date values in the error message (optional, defaults to true). If set to true, it will use the default locale of the environment. You can also pass an Intl.LocalesArgument to specify a custom locale. | | numberLocalization | boolean \| Intl.LocalesArgument | Indicates whether to localize number values in the error message (optional, defaults to true). If set to true, it will use the default locale of the environment. You can also pass an Intl.LocalesArgument to specify a custom locale. |

Example

import { createErrorMap } from 'zod-validation-error/v4';

const messageBuilder = createErrorMap({
  includePath: false,
  maxAllowedValuesToDisplay: 3,
});

createMessageBuilder

Creates zod-validation-error's default MessageBuilder, which is used to produce user-friendly error messages.

Meant to be passed as an option to fromError, fromZodIssue, fromZodError or toValidationError.

Arguments

  • options - Object; formatting options (optional) | Name | Type | Description | | ---- | :----: | ----------- | | maxIssuesInMessage | number | Max issues to include in user-friendly message (optional, defaults to 99) | | issueSeparator | string | Used to concatenate issues in user-friendly message (optional, defaults to ";") | | prefix | string \| undefined | Prefix to use in user-friendly message (optional, defaults to "Validation error"). Pass undefined to disable prefix completely. | | prefixSeparator | string | Used to concatenate prefix with rest of the user-friendly message (optional, defaults to ": "). Not used when prefix is undefined. | | error | ErrorMap | Accepts an errorMap to format individual issues into user-friendly error messages (optional, defaults to undefined). Note that this is an optional property and if not provided, the default error map will be used. Also, you don't need to pass zod-validation-error's errorMap here; you can use your own custom errorMap if you want. |

Example

import { createErrorMap, createMessageBuilder } from 'zod-validation-error/v4';

const messageBuilder = createMessageBuilder({
  maxIssuesInMessage: 3,
  error: createErrorMap({
    includePath: false,
  }),
});

isValidationError

A type guard utility function, based on instanceof comparison.

Arguments

  • error - error instance (required)

Example

import { z as zod } from 'zod/v4';
import { ValidationError, isValidationError } from 'zod-validation-error/v4';

const err = new ValidationError('foobar');
isValidationError(err); // returns true

const invalidErr = new Error('foobar');
isValidationError(err); // returns false

isValidationErrorLike

A type guard utility function, based on heuristics comparison.

Why do we need heuristics since we can use a simple instanceof comparison? Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older zod-validation-error version internally. In such case, the instanceof comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.

tl;dr if you are uncertain then it is preferable to use isValidationErrorLike instead of isValidationError.

Arguments

  • error - error instance (required)

Example

import {
  ValidationError,
  isValidationErrorLike,
} from 'zod-validation-error/v4';

const err = new ValidationError('foobar');
isValidationErrorLike(err); // returns true

const invalidErr = new Error('foobar');
isValidationErrorLike(err); // returns false

isZodErrorLike

A type guard utility function, based on heuristics comparison.

Why do we need heuristics since we can use a simple instanceof comparison? Because of multi-version inconsistencies. For instance, it's possible that a dependency is using an older zod version internally. In such case, the instanceof comparison will yield invalid results because module deduplication does not apply at npm/yarn level and the prototype is different.

Arguments

  • error - error instance (required)

Example

import { z as zod } from 'zod/v4';
import { ValidationError, isZodErrorLike } from 'zod-validation-error/v4';

const zodValidationErr = new ValidationError('foobar');
isZodErrorLike(zodValidationErr); // returns false

const genericErr = new Error('foobar');
isZodErrorLike(genericErr); // returns false

const zodErr = new zod.ZodError([
  {
    origin: 'number',
    code: 'too_small',
    minimum: 0,
    inclusive: false,
    path: ['id'],
    message: 'Number must be greater than 0 at "id"',
    input: -1,
  },
]);
isZodErrorLike(zodErr); // returns true

fromError

Converts an error to ValidationError.

What is the difference between fromError and fromZodError? The fromError function is a less strict version of fromZodError. It can accept an unknown error and attempt to convert it to a ValidationError.

Arguments

  • error - unknown; an error (required)
  • options - Object; formatting options (optional)
    • messageBuilder - MessageBuilder; a function that accepts an array of zod.ZodIssue objects and returns a user-friendly error message in the form of a string (optional).

Notes

Alternatively, you may pass createMessageBuilder options directly as options. These will be used as arguments to create the MessageBuilder instance internally.

fromZodIssue

Converts a single zod issue to ValidationError.

Arguments

  • zodIssue - zod.ZodIssue; a ZodIssue instance (required)
  • options - Object; formatting options (optional)
    • messageBuilder - MessageBuilder; a function that accepts an array of zod.ZodIssue objects and returns a user-friendly error message in the form of a string (optional).

Notes

Alternatively, you may pass createMessageBuilder options directly as options. These will be used as arguments to create the MessageBuilder instance internally.

fromZodError

Converts zod error to ValidationError.

Why is the difference between ZodError and ZodIssue? A ZodError is a collection of 1 or more ZodIssue instances. It's what you get when you call zodSchema.parse().

Arguments

  • zodError - zod.ZodError; a ZodError instance (required)
  • options - Object; formatting options (optional)
    • messageBuilder - MessageBuilder; a function that accepts an array of zod.ZodIssue objects and returns a user-friendly error message in the form of a string (optional).

Notes

Alternatively, you may pass createMessageBuilder options directly as options. These will be used as arguments to create the MessageBuilder instance internally.

toValidationError

A curried version of fromZodError meant to be used for FP (Functional Programming). Note it first takes the options object if needed and returns a function that converts the zodError to a ValidationError object

toValidationError(options) => (zodError) => ValidationError

Example using fp-ts

import * as Either from 'fp-ts/Either';
import { z as zod } from 'zod/v4';
import { toValidationError, ValidationError } from 'zod-validation-error/v4';

// create zod schema
const zodSchema = zod
  .object({
    id: zod.int().positive(),
    email: zod.email(),
  })
  .brand<'User'>();

export type User = zod.infer<typeof zodSchema>;

export function parse(
  value: zod.input<typeof zodSchema>
): Either.Either<ValidationError, User> {
  return Either.tryCatch(() => schema.parse(value), toValidationError());
}

FAQ

What is the difference between zod-validation-error and zod's own prettifyError?

While both libraries aim to provide a human-readable string representation of a zod error, they differ in several ways...

  1. End-user focus: zod-validation-error provides opinionated, user-friendly error messages designed to be displayed directly to end-users in forms or API responses, whereas Zod's native error handling seem more developer-focused.
  2. Customization options: zod-validation-error offers extensive configuration for message formatting, such as controlling path inclusion, allowed values display, localization, and more.
  3. Error handling: zod-validation-error maintains the original error details while providing a clean, consistent interface through the ValidationError class.
  4. Integration flexibility: Beyond just formatting, zod-validation-error provides utility functions for error detection and conversion that work well in various architectural patterns, e.g. functional programming.

Disclaimer: as per this comment, we have no intention to antagonize zod. In fact, we are happy to decommission this module assuming it's in the best interest of the community. As of now, it seems that there's room for both zod-validation-error and prettifyError, also based on Colin McDonnell's response.

How to distinguish between errors

Use the isValidationErrorLike type guard.

Example

Scenario: Distinguish between ValidationError VS generic Error in order to respond with 400 VS 500 HTTP status code respectively.

import { isValidationErrorLike } from 'zod-validation-error/v4';

try {
  func(); // throws Error - or - ValidationError
} catch (err) {
  if (isValidationErrorLike(err)) {
    return 400; // Bad Data (this is a client error)
  }

  return 500; // Server Error
}

How to use ValidationError outside zod

It's possible to implement custom validation logic outside zod and throw a ValidationError.

Example 1: passing custom message

import { ValidationError } from 'zod-validation-error/v4';
import { Buffer } from 'node:buffer';

function parseBuffer(buf: unknown): Buffer {
  if (!Buffer.isBuffer(buf)) {
    throw new ValidationError('Invalid argument; expected buffer');
  }

  return buf;
}

Example 2: passing custom message and original error as cause

import { ValidationError } from 'zod-validation-error/v4';

try {
  // do something that throws an error
} catch (err) {
  throw new ValidationError('Something went deeply wrong', { cause: err });
}

How to use ValidationError with custom "error map"

Zod supports customizing error messages by providing a custom "error map". You may combine this with zod-validation-error to produce user-friendly messages.

Example 1: produce user-friendly error messages using the errorMap property

If all you need is to produce user-friendly error messages you may use the errorMap property.

import { z as zod } from 'zod/v4';
import { fromError, createErrorMap } from 'zod-validation-error/v4';

zod.config({
  customError: createErrorMap({
    includePath: true,
  }),
});

Does zod-validation-error support CommonJS

Yes, zod-validation-error supports CommonJS out-of-the-box. All you need to do is import it using require.

Example

const { ValidationError } = require('zod-validation-error/v4');

Contribute

Source code contributions are most welcome. Please open a PR, ensure the linter is satisfied and all tests pass.

We are hiring

Causaly is building the world's largest biomedical knowledge platform, using technologies such as TypeScript, React and Node.js. Find out more about our openings at https://jobs.ashbyhq.com/causaly.

License

MIT

更新日志

@causaly/zod-validation-error

3.5.3

Patch Changes

  • 7bae962: Add support for zod v4 as peer dependency.

3.5.2

Patch Changes

  • 3809f85: Include paths of sub-issues of union.

3.5.1

Patch Changes

  • e7713d5: Add compatibility with older node versions and module-resolution strategies + improve docs

3.5.0

Minor Changes

  • bf72012: Add support for zod v4

3.4.1

Patch Changes

  • 94d5f3b: Bump zod to v.3.24.4 in package.json as dev + peer dependency

3.4.0

Minor Changes

  • 3a7928c: Customize error messages using a MessageBuilder.

3.3.1

Patch Changes

  • 42bc4fe: Test Version Packages fix

3.3.0

Minor Changes

  • 66f5b5d: Match ZodError via heuristics instead of relying on instanceof.

    Why? Because we want to ensure that zod-validation-error works smoothly even when multiple versions of zod have been installed in the same project.

3.2.0

Minor Changes

  • 6b4e8a0: Introduce fromError API which is a less strict version of fromZodError
  • 35a28c6: Add runtime check in fromZodError and throw dev-friendly TypeError suggesting usage of fromError instead

3.1.0

Minor Changes

  • 3f5e391: Better error messages for zod.function() types

3.0.3

Patch Changes

  • 2f1ef27: Bundle code as a single index.js (cjs) or index.mjs (esm) file. Restore exports configuration in package.json.

3.0.2

Patch Changes

  • 24b773c: Revert package.json exports causing dependant projects to fail

3.0.1

Patch Changes

  • 3382fbc: 1. Fix issue with ErrorOptions not being found in earlier to es2022 typescript configs. 2. Add exports definition to package.json to help bundlers (e.g. rollup) identify the right module to use.

3.0.0

Major Changes

  • deb4639: BREAKING CHANGE: Refactor ValidationError to accept ErrorOptions as second parameter.

    What changed?

    Previously, ValidationError accepted Array<ZodIssue> as 2nd parameter. Now, it accepts ErrorOptions which contains a cause property. If cause is a ZodError then it will extract the attached issues and expose them over error.details.

    Why?

    This change allows us to use ValidationError like a native JavaScript Error. For example, we can now do:

    import { ValidationError } from 'zod-validation-error';
    
    try {
      // attempt to do something that might throw an error
    } catch (err) {
      throw new ValidationError('Something went deeply wrong', { cause: err });
    }
    

    How can you update your code?

    If you are using ValidationError directly, then you need to update your code to pass ErrorOptions as a 2nd parameter.

    import { ValidationError } from 'zod-validation-error';
    
    // before
    const err = new ValidationError('Something went wrong', zodError.issues);
    
    // after
    const err = new ValidationError('Something went wrong', { cause: zodError });
    

    If you were never using ValidationError directly, then you don't need to do anything.

2.1.0

Minor Changes

  • b084ad5: Add includePath option to allow users take control on whether to include the erroneous property name in their error messages.

2.0.0

Major Changes

  • b199ca1: Update toValidationError() to return only ValidationError instances

    This change only affects users of toValidationError(). The method was previously returning Error | ValidationError and now returns only ValidationError.

1.5.0

Minor Changes

  • 82b7739: Expose errorMap property to use with zod.setErrorMap() method

1.4.0

Minor Changes

  • 8893d16: Expose fromZodIssue method

1.3.1

Patch Changes

  • 218da5f: fix: casing typo of how zod namespace was referenced

1.3.0

Minor Changes

  • 8ccae09: Added exports of types for parameters of fromZodError function

1.2.1

Patch Changes

  • 449477d: Switch to using npm instead of yarn. Update node requirement to v.16+

1.2.0

Minor Changes

  • f3aa0b2: Better handling for single-item paths

    Given a validation error at array position 1 the error output would read Error X at "[1]". After this change, the error output reads Error X at index 1.

    Likewise, previously a validation error at property "" would yield `Error X at "[""]". Now it yieldsError X at "*"` which reads much better.

1.1.0

Minor Changes

  • b693f52: Handle unicode and special-character identifiers

1.0.1

Patch Changes

  • b868741: Fix broken links in API docs

1.0.0

Major Changes

  • 90b2f83: Update ZodValidationError to behave more like a native Error constructor. Make options argument optional. Add name property and define toString() method.

0.3.2

Patch Changes

  • a2e5322: Ensure union errors do not output duplicate messages

0.3.1

Patch Changes

  • 9c4c4ec: Make union errors more detailed

0.3.0

Minor Changes

  • 59ad8df: Expose isValidationErrorLike type-guard

0.2.2

Patch Changes

  • fa81c9b: Drop SWC; Fix ESM export

0.2.1

Patch Changes

  • 7f420d1: Update build and npm badges on README.md

0.2.0

Minor Changes

  • fde2f50: update dependency in package json so the user does not have to manually install it, will be installed on package install.

0.1.1

Patch Changes

  • 67336ac: Enable automatic release to npm

0.1.0

Minor Changes

  • fcda684: Initial functionality