{"name":"zod-validation-error","version":"3.5.2","keywords":["zod","error","validation"],"author":{"url":"https://github.com/jmike","name":"Dimitrios C. Michalakos","email":"dimitris@jmike.gr"},"license":"MIT","_id":"zod-validation-error@3.5.2","maintainers":[{"name":"jmike","email":"dimitris@jmike.gr"},{"name":"dnlytras","email":"dnlytras@gmail.com"},{"name":"nikoskalogridis","email":"nikos.kalogridis@gmail.com"},{"name":"thanoskrg","email":"hey@maestros.io"}],"contributors":[{"url":"https://github.com/thanoskrg","name":"Thanos Karagiannis","email":"hey@maestros.io"},{"url":"https://github.com/NikosTsompanides","name":"Nikos Tsompanides","email":"nikostsompanides@gmail.com"},{"url":"https://github.com/nikoskalogridis","name":"Nikos Kalogridis"}],"homepage":"https://github.com/causaly/zod-validation-error#readme","bugs":{"url":"https://github.com/causaly/zod-validation-error/issues"},"dist":{"shasum":"5af463c1acd4662e6b2610a75260931dbcb43a56","tarball":"http://registry-npm.ywwl.com/zod-validation-error/download/zod-validation-error-3.5.2.tgz","fileCount":16,"integrity":"sha512-mdi7YOLtram5dzJ5aDtm1AG9+mxRma1iaMrZdYIpFO7epdKBUwLHIxTF8CPDeCQ828zAXYtizrKlEJAtzgfgrw==","signatures":[{"sig":"MEUCIQCMMDCxyVC/7BVw8jBjUhjybC6LzLoht4eWbkAQsgNTqQIgegUcSPMoAHpVfNK0pBPMSCAJBaPuJ5D9y6vR12KH6bw=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":226324,"size":39668,"noattachment":false,"key":"/zod-validation-error/-/zod-validation-error-3.5.2.tgz"},"main":"./v3/index.js","types":"./v3/index.d.ts","module":"./v3/index.mjs","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./v3/index.d.ts","import":"./v3/index.mjs","require":"./v3/index.js"},"./v3":{"types":"./v3/index.d.ts","import":"./v3/index.mjs","require":"./v3/index.js"},"./v4":{"types":"./v4/index.d.ts","import":"./v4/index.mjs","require":"./v4/index.js"}},"gitHead":"f44017bfd0308fad3cebeaf87ffedf16de98af30","scripts":{"lint":"eslint lib --ext .ts","test":"vitest run","build":"tsup --config ./tsup.config.ts","format":"prettier --config ./.prettierrc --ignore-path .gitignore -w .","prepare":"husky","release":"changeset publish","changeset":"changeset","typecheck":"tsc --noEmit","prerelease":"npm run build && npm run test"},"_npmUser":{"name":"jmike","actor":{"name":"jmike","type":"user","email":"dimitris@jmike.gr"},"email":"dimitris@jmike.gr"},"repository":{"url":"git://github.com/causaly/zod-validation-error.git","type":"git"},"_npmVersion":"10.8.2","description":"Wrap zod validation errors in user-friendly readable messages","directories":{},"lint-staged":{"*.{js,jsx,ts,tsx}":["eslint --fix","prettier --config ./.prettierrc.json --write"]},"sideEffects":false,"_nodeVersion":"20.19.2","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"zod":"^3.25.62","tsup":"^8.0.2","husky":"^9.1.7","eslint":"^8.4.1","vitest":"^3.1.2","prettier":"^2.8.8","typescript":"^5.1.6","@types/node":"^20.5.0","lint-staged":"^15.0.1","concurrently":"^8.2.0","@changesets/cli":"^2.27.7","@commitlint/cli":"^18.0.0","eslint-plugin-import":"^2.29.1","eslint-config-prettier":"^9.0.0","eslint-plugin-prettier":"^4.2.1","@typescript-eslint/parser":"^6.4.1","@changesets/changelog-github":"^0.5.0","@commitlint/config-conventional":"^18.0.0","@typescript-eslint/eslint-plugin":"^6.4.1"},"peerDependencies":{"zod":"^3.25.0"},"_npmOperationalInternal":{"tmp":"tmp/zod-validation-error_3.5.2_1750230086977_0.5672978327728035","host":"s3://npm-registry-packages-npm-production"},"readme":"# zod-validation-error\n\nWrap zod validation errors in user-friendly readable messages.\n\n[![Build Status](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml/badge.svg)](https://github.com/causaly/zod-validation-error/actions/workflows/ci.yml) [![npm version](https://img.shields.io/npm/v/zod-validation-error.svg?color=0c0)](https://www.npmjs.com/package/zod-validation-error)\n\n#### Features\n\n- User-friendly readable messages, configurable via options;\n- Maintain original issues under `error.details`;\n- Supports both `zod` v3 and v4.\n\n**_Note:_** This is the v3 version of `zod-validation-error`. If you are looking for zod v4 support, please click [here](/README.md).\n\n## Installation\n\n```bash\nnpm install zod-validation-error\n```\n\n#### Requirements\n\n- Node.js v.18+\n- TypeScript v.4.5+\n\n## Quick start\n\n```typescript\nimport { z as zod } from 'zod/v3';\nimport { fromError } from 'zod-validation-error/v3';\n\n// create zod schema\nconst zodSchema = zod.object({\n  id: zod.number().int().positive(),\n  email: zod.string().email(),\n});\n\n// parse some invalid value\ntry {\n  zodSchema.parse({\n    id: 1,\n    email: 'foobar', // note: invalid email\n  });\n} catch (err) {\n  const validationError = fromError(err);\n  // the error is now readable by the user\n  // you may print it to console\n  console.log(validationError.toString());\n  // or return it as an actual error\n  return validationError;\n}\n```\n\n## Motivation\n\nZod 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.\n\n### Example\n\n#### Input (from Zod)\n\n```json\n[\n  {\n    \"code\": \"too_small\",\n    \"inclusive\": false,\n    \"message\": \"Number must be greater than 0\",\n    \"minimum\": 0,\n    \"path\": [\"id\"],\n    \"type\": \"number\"\n  },\n  {\n    \"code\": \"invalid_string\",\n    \"message\": \"Invalid email\",\n    \"path\": [\"email\"],\n    \"validation\": \"email\"\n  }\n]\n```\n\n#### Output\n\n```\nValidation error: Number must be greater than 0 at \"id\"; Invalid email at \"email\"\n```\n\n## API\n\n- [ValidationError(message[, options])](#validationerror)\n- [createMessageBuilder(props)](#createMessageBuilder)\n- [errorMap](#errormap)\n- [isValidationError(error)](#isvalidationerror)\n- [isValidationErrorLike(error)](#isvalidationerrorlike)\n- [isZodErrorLike(error)](#iszoderrorlike)\n- [fromError(error[, options])](#fromerror)\n- [fromZodIssue(zodIssue[, options])](#fromzodissue)\n- [fromZodError(zodError[, options])](#fromzoderror)\n- [toValidationError([options]) => (error) => ValidationError](#tovalidationerror)\n\n### ValidationError\n\nMain `ValidationError` class, extending native JavaScript `Error`.\n\n#### Arguments\n\n- `message` - _string_; error message (required)\n- `options` - _ErrorOptions_; error options as per [JavaScript definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#options) (optional)\n  - `options.cause` - _any_; can be used to hold the original zod error (optional)\n\n#### Example 1: construct new ValidationError with `message`\n\n```typescript\nconst { ValidationError } = require('zod-validation-error');\n\nconst error = new ValidationError('foobar');\nconsole.log(error instanceof Error); // prints true\n```\n\n#### Example 2: construct new ValidationError with `message` and `options.cause`\n\n```typescript\nimport { z as zod } from 'zod/v3';\nconst { ValidationError } = require('zod-validation-error');\n\nconst error = new ValidationError('foobar', {\n  cause: new zod.ZodError([\n    {\n      code: 'invalid_string',\n      message: 'Invalid email',\n      path: ['email'],\n      validation: 'email',\n    },\n  ]),\n});\n\nconsole.log(error.details); // prints issues from zod error\n```\n\n### createMessageBuilder\n\nCreates zod-validation-error's default `MessageBuilder`, which is used to produce user-friendly error messages.\n\nMeant to be passed as an option to [fromError](#fromerror), [fromZodIssue](#fromzodissue), [fromZodError](#fromzoderror) or [toValidationError](#tovalidationerror).\n\nYou may read more on the concept of the `MessageBuilder` further [below](#MessageBuilder).\n\n#### Arguments\n\n- `props` - _Object_; formatting options (optional)\n  - `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\n#### Example\n\n```typescript\nimport { createMessageBuilder } from 'zod-validation-error/v3';\n\nconst messageBuilder = createMessageBuilder({\n  includePath: false,\n  maxIssuesInMessage: 3,\n});\n```\n\n### errorMap\n\nA custom error map to use with zod's `setErrorMap` method and get user-friendly messages automatically.\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod/v3';\nimport { errorMap } from 'zod-validation-error/v3';\n\nzod.setErrorMap(errorMap);\n```\n\n### isValidationError\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on `instanceof` comparison.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod/v3';\nimport { ValidationError, isValidationError } from 'zod-validation-error/v3';\n\nconst err = new ValidationError('foobar');\nisValidationError(err); // returns true\n\nconst invalidErr = new Error('foobar');\nisValidationError(err); // returns false\n```\n\n### isValidationErrorLike\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.\n\n_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.\n\ntl;dr if you are uncertain then it is preferable to use `isValidationErrorLike` instead of `isValidationError`.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport {\n  ValidationError,\n  isValidationErrorLike,\n} from 'zod-validation-error/v3';\n\nconst err = new ValidationError('foobar');\nisValidationErrorLike(err); // returns true\n\nconst invalidErr = new Error('foobar');\nisValidationErrorLike(err); // returns false\n```\n\n### isZodErrorLike\n\nA [type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) utility function, based on _heuristics_ comparison.\n\n_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.\n\n#### Arguments\n\n- `error` - error instance (required)\n\n#### Example\n\n```typescript\nimport { z as zod } from 'zod/v3';\nimport { ValidationError, isZodErrorLike } from 'zod-validation-error/v3';\n\nconst zodValidationErr = new ValidationError('foobar');\nisZodErrorLike(zodValidationErr); // returns false\n\nconst genericErr = new Error('foobar');\nisZodErrorLike(genericErr); // returns false\n\nconst zodErr = new zod.ZodError([\n  {\n    code: zod.ZodIssueCode.custom,\n    path: [],\n    message: 'foobar',\n    fatal: true,\n  },\n]);\nisZodErrorLike(zodErr); // returns true\n```\n\n### fromError\n\nConverts an error to `ValidationError`.\n\n_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`.\n\n#### Arguments\n\n- `error` - _unknown_; an error (required)\n- `options` - _Object_; formatting options (optional)\n  - `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).\n\n#### Notes\n\nAlternatively, you may pass the following `options` instead of a `messageBuilder`.\n\n- `options` - _Object_; formatting options (optional)\n  - `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\nThey will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.\n\n### fromZodIssue\n\nConverts a single zod issue to `ValidationError`.\n\n#### Arguments\n\n- `zodIssue` - _zod.ZodIssue_; a ZodIssue instance (required)\n- `options` - _Object_; formatting options (optional)\n  - `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).\n\n#### Notes\n\nAlternatively, you may pass the following `options` instead of a `messageBuilder`.\n\n- `options` - _Object_; formatting options (optional)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\nThey will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.\n\n### fromZodError\n\nConverts zod error to `ValidationError`.\n\n_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()`.\n\n#### Arguments\n\n- `zodError` - _zod.ZodError_; a ZodError instance (required)\n- `options` - _Object_; formatting options (optional)\n  - `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).\n\n#### Notes\n\nAlternatively, you may pass the following `options` instead of a `messageBuilder`.\n\n- `options` - _Object_; formatting options (optional)\n  - `maxIssuesInMessage` - _number_; max issues to include in user-friendly message (optional, defaults to 99)\n  - `issueSeparator` - _string_; used to concatenate issues in user-friendly message (optional, defaults to \";\")\n  - `unionSeparator` - _string_; used to concatenate union-issues in user-friendly message (optional, defaults to \", or\")\n  - `prefix` - _string_ or _null_; prefix to use in user-friendly message (optional, defaults to \"Validation error\"). Pass `null` to disable prefix completely.\n  - `prefixSeparator` - _string_; used to concatenate prefix with rest of the user-friendly message (optional, defaults to \": \"). Not used when `prefix` is `null`.\n  - `includePath` - _boolean_; used to provide control on whether to include the erroneous property name suffix or not (optional, defaults to `true`).\n\nThey will be passed as arguments to the [createMessageBuilder](#createMessageBuilder) function. The only reason they exist is to provide backwards-compatibility with older versions of `zod-validation-error`. They should however be considered deprecated and may be removed in the future.\n\n### toValidationError\n\nA 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\n\n```js\ntoValidationError(options) => (zodError) => ValidationError\n```\n\n#### Example using fp-ts\n\n```typescript\nimport * as Either from 'fp-ts/Either';\nimport { z as zod } from 'zod/v3';\nimport { toValidationError, ValidationError } from 'zod-validation-error/v3';\n\n// create zod schema\nconst zodSchema = zod\n  .object({\n    id: zod.number().int().positive(),\n    email: zod.string().email(),\n  })\n  .brand<'User'>();\n\nexport type User = zod.infer<typeof zodSchema>;\n\nexport function parse(\n  value: zod.input<typeof zodSchema>\n): Either.Either<ValidationError, User> {\n  return Either.tryCatch(() => schema.parse(value), toValidationError());\n}\n```\n\n## MessageBuilder\n\n`zod-validation-error` can be configured with a custom `MessageBuilder` function in order to produce case-specific error messages.\n\n#### Example\n\nFor instance, one may want to print `invalid_string` errors to the console in red color.\n\n```typescript\nimport { z as zod } from 'zod/v3';\nimport { type MessageBuilder, fromError } from 'zod-validation-error/v3';\nimport chalk from 'chalk';\n\n// create custom MessageBuilder\nconst myMessageBuilder: MessageBuilder = (issues) => {\n  return (\n    issues\n      // format error message\n      .map((issue) => {\n        if (issue.code === zod.ZodIssueCode.invalid_string) {\n          return chalk.red(issue.message);\n        }\n\n        return issue.message;\n      })\n      // join as string with new-line character\n      .join('\\n')\n  );\n};\n\n// create zod schema\nconst zodSchema = zod.object({\n  id: zod.number().int().positive(),\n  email: zod.string().email(),\n});\n\n// parse some invalid value\ntry {\n  zodSchema.parse({\n    id: 1,\n    email: 'foobar', // note: invalid email value\n  });\n} catch (err) {\n  const validationError = fromError(err, {\n    messageBuilder: myMessageBuilder,\n  });\n  // the error is now displayed with red letters\n  console.log(validationError.toString());\n}\n```\n\n## FAQ\n\n### How to distinguish between errors\n\nUse the `isValidationErrorLike` type guard.\n\n#### Example\n\nScenario: Distinguish between `ValidationError` VS generic `Error` in order to respond with 400 VS 500 HTTP status code respectively.\n\n```typescript\nimport * as Either from 'fp-ts/Either';\nimport { z as zod } from 'zod/v3';\nimport { isValidationErrorLike } from 'zod-validation-error/v3';\n\ntry {\n  func(); // throws Error - or - ValidationError\n} catch (err) {\n  if (isValidationErrorLike(err)) {\n    return 400; // Bad Data (this is a client error)\n  }\n\n  return 500; // Server Error\n}\n```\n\n### How to use `ValidationError` outside `zod`\n\nIt's possible to implement custom validation logic outside `zod` and throw a `ValidationError`.\n\n#### Example 1: passing custom message\n\n```typescript\nimport { ValidationError } from 'zod-validation-error/v3';\nimport { Buffer } from 'node:buffer';\n\nfunction parseBuffer(buf: unknown): Buffer {\n  if (!Buffer.isBuffer(buf)) {\n    throw new ValidationError('Invalid argument; expected buffer');\n  }\n\n  return buf;\n}\n```\n\n#### Example 2: passing custom message and original error as cause\n\n```typescript\nimport { ValidationError } from 'zod-validation-error/v3';\n\ntry {\n  // do something that throws an error\n} catch (err) {\n  throw new ValidationError('Something went deeply wrong', { cause: err });\n}\n```\n\n### How to use `ValidationError` with custom \"error map\"\n\nZod supports customizing error messages by providing a custom \"error map\". You may combine this with `zod-validation-error` to produce user-friendly messages.\n\n#### Example 1: produce user-friendly error messages using the `errorMap` property\n\nIf all you need is to produce user-friendly error messages you may use the `errorMap` property.\n\n```typescript\nimport { z as zod } from 'zod/v3';\nimport { errorMap } from 'zod-validation-error/v3';\n\nzod.setErrorMap(errorMap);\n```\n\n#### Example 2: extra customization using `fromZodIssue`\n\nIf you need to customize some error code, you may use the `fromZodIssue` function.\n\n```typescript\nimport { z as zod } from 'zod/v3';\nimport { fromZodIssue } from 'zod-validation-error/v3';\n\nconst customErrorMap: zod.ZodErrorMap = (issue, ctx) => {\n  switch (issue.code) {\n    case ZodIssueCode.invalid_type: {\n      return {\n        message:\n          'Custom error message of your preference for invalid_type errors',\n      };\n    }\n    default: {\n      const validationError = fromZodIssue({\n        ...issue,\n        // fallback to the default error message\n        // when issue does not have a message\n        message: issue.message ?? ctx.defaultError,\n      });\n\n      return {\n        message: validationError.message,\n      };\n    }\n  }\n};\n\nzod.setErrorMap(customErrorMap);\n```\n\n### How to use `zod-validation-error` with `react-hook-form`?\n\n```typescript\nimport { useForm } from 'react-hook-form';\nimport { zodResolver } from '@hookform/resolvers/zod';\nimport { errorMap } from 'zod-validation-error/v3';\n\nuseForm({\n  resolver: zodResolver(schema, { errorMap }),\n});\n```\n\n### Does `zod-validation-error` support CommonJS\n\nYes, `zod-validation-error` supports CommonJS out-of-the-box. All you need to do is import it using `require`.\n\n#### Example\n\n```typescript\nconst { ValidationError } = require('zod-validation-error');\n```\n\n## Contribute\n\nSource code contributions are most welcome. Please open a PR, ensure the linter is satisfied and all tests pass.\n\n#### We are hiring\n\nCausaly 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.\n\n## License\n\nMIT\n","publish_time":1750230087174,"_cnpm_publish_time":1750230087174,"dist-tags":{"beta":"4.0.0-beta.2","latest":"5.0.0"}}