{"id":13632220,"url":"https://github.com/causaly/zod-validation-error","last_synced_at":"2025-04-18T02:32:08.137Z","repository":{"id":58213937,"uuid":"530578345","full_name":"causaly/zod-validation-error","owner":"causaly","description":"Wrap zod validation errors in user-friendly readable messages","archived":false,"fork":false,"pushed_at":"2025-04-07T15:17:49.000Z","size":1945,"stargazers_count":906,"open_issues_count":2,"forks_count":15,"subscribers_count":14,"default_branch":"main","last_synced_at":"2025-04-12T05:37:08.182Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/causaly.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-08-30T09:06:34.000Z","updated_at":"2025-04-11T07:32:02.000Z","dependencies_parsed_at":"2023-10-16T23:15:07.802Z","dependency_job_id":"baca3b3a-7b4e-4e95-8563-d54d053c9249","html_url":"https://github.com/causaly/zod-validation-error","commit_stats":{"total_commits":40,"total_committers":9,"mean_commits":4.444444444444445,"dds":0.475,"last_synced_commit":"97fa2cb92ebb42f530e257cb5ec09422f71e20a7"},"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/causaly%2Fzod-validation-error","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/causaly%2Fzod-validation-error/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/causaly%2Fzod-validation-error/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/causaly%2Fzod-validation-error/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/causaly","download_url":"https://codeload.github.com/causaly/zod-validation-error/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249414252,"owners_count":21267724,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T22:02:56.765Z","updated_at":"2025-04-18T02:32:07.280Z","avatar_url":"https://github.com/causaly.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"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- Extensive tests.\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';\nimport { fromError } from 'zod-validation-error';\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]) =\u003e (error) =\u003e 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';\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';\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';\nimport { errorMap } from 'zod-validation-error';\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';\nimport { ValidationError, isValidationError } from 'zod-validation-error';\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 { ValidationError, isValidationErrorLike } from 'zod-validation-error';\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';\nimport { ValidationError, isZodErrorLike } from 'zod-validation-error';\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)\nuser-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) =\u003e (zodError) =\u003e ValidationError\n```\n\n#### Example using fp-ts\n\n```typescript\nimport * as Either from 'fp-ts/Either';\nimport { z as zod } from 'zod';\nimport { toValidationError, ValidationError } from 'zod-validation-error';\n\n// create zod schema\nconst zodSchema = zod\n  .object({\n    id: zod.number().int().positive(),\n    email: zod.string().email(),\n  })\n  .brand\u003c'User'\u003e();\n\nexport type User = zod.infer\u003ctypeof zodSchema\u003e;\n\nexport function parse(\n  value: zod.input\u003ctypeof zodSchema\u003e\n): Either.Either\u003cValidationError, User\u003e {\n  return Either.tryCatch(() =\u003e 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';\nimport { type MessageBuilder, fromError } from 'zod-validation-error';\nimport chalk from 'chalk';\n\n// create custom MessageBuilder\nconst myMessageBuilder: MessageBuilder = (issues) =\u003e {\n  return issues\n    // format error message\n    .map((issue) =\u003e {\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// 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\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';\nimport { isValidationErrorLike } from 'zod-validation-error';\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';\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';\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';\nimport { errorMap } from 'zod-validation-error';\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';\nimport { fromZodIssue } from 'zod-validation-error';\n\nconst customErrorMap: zod.ZodErrorMap = (issue, ctx) =\u003e {\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';\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://apply.workable.com/causaly/.\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcausaly%2Fzod-validation-error","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcausaly%2Fzod-validation-error","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcausaly%2Fzod-validation-error/lists"}