{"id":13998566,"url":"https://github.com/chrishoermann/zod-prisma-types","last_synced_at":"2025-05-14T02:04:55.509Z","repository":{"id":64170222,"uuid":"565815024","full_name":"chrishoermann/zod-prisma-types","owner":"chrishoermann","description":"Generator creates zod types for your prisma models with advanced validation","archived":false,"fork":false,"pushed_at":"2025-02-08T20:38:38.000Z","size":20003,"stargazers_count":763,"open_issues_count":95,"forks_count":62,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-15T01:59:50.128Z","etag":null,"topics":["code-generation","generator","prisma","validator","zod"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chrishoermann.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":"FUNDING.yml","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,"zenodo":null},"funding":{"github":"chrishoermann"}},"created_at":"2022-11-14T11:39:16.000Z","updated_at":"2025-04-14T09:26:21.000Z","dependencies_parsed_at":"2023-10-14T18:56:33.601Z","dependency_job_id":"fc847dbe-a9fd-4490-ba2a-d169cfad762a","html_url":"https://github.com/chrishoermann/zod-prisma-types","commit_stats":{"total_commits":382,"total_committers":16,"mean_commits":23.875,"dds":"0.13089005235602091","last_synced_commit":"a34b9f3cb04572185c598a692f62930337c3ca04"},"previous_names":[],"tags_count":82,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrishoermann%2Fzod-prisma-types","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrishoermann%2Fzod-prisma-types/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrishoermann%2Fzod-prisma-types/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrishoermann%2Fzod-prisma-types/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chrishoermann","download_url":"https://codeload.github.com/chrishoermann/zod-prisma-types/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254052691,"owners_count":22006716,"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":["code-generation","generator","prisma","validator","zod"],"created_at":"2024-08-09T19:01:47.150Z","updated_at":"2025-05-14T02:04:55.468Z","avatar_url":"https://github.com/chrishoermann.png","language":"TypeScript","funding_links":["https://github.com/sponsors/chrishoermann","https://www.buymeacoffee.com/chrishoermann"],"categories":["TypeScript","others"],"sub_categories":[],"readme":"[![NPM version](https://img.shields.io/npm/v/zod-prisma-types?style=for-the-badge)](https://www.npmjs.com/package/zod-prisma-types)\n[![Stars](https://img.shields.io/github/stars/chrishoermann/zod-prisma-types?style=for-the-badge)](https://github.com/chrishoermann/zod-prisma-types/stargazers)\n[![Contirbutors](https://img.shields.io/github/contributors/chrishoermann/zod-prisma-types?style=for-the-badge)](https://github.com/chrishoermann/zod-prisma-types/graphs/contributors)\n[![License](https://img.shields.io/badge/license-MIT-green?style=for-the-badge)](https://github.com/chrishoermann/zod-prisma-types/blob/master/LICENSE)\n[![Issues](https://img.shields.io/github/issues/chrishoermann/zod-prisma-types?style=for-the-badge)](https://github.com/chrishoermann/zod-prisma-types/issues)\n\n# zod-prisma-types \u003c!-- omit from toc --\u003e\n\n`zod-prisma-types` is a generator for [prisma](www.prisma.io) that generates [zod](https://github.com/colinhacks/zod) schemas from your prisma models. This includes schemas of models, enums, inputTypes, argTypes, filters and so on. It also provides options to write advanced zod validators directly in the Prisma schema comments.\n\nSince I'm maintaining the generator in my spare time consider buying me a coffee or sponsoring me if you like the project. Thanks!\n\n[![\"Buy Me A Coffee\"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/chrishoermann)\n\n## Supported versions\n\nCurrently this package supports Prisma versions 4.x - 6.x.\n\n## Breaking changes in v2.x.x\u003c!-- omit from toc --\u003e\n\nBe aware that some generator options have been removed, a few new ones have been added, the behavior of custom imports has changed and ts-morph is no longer needed to generate files in v2.0.0.\n\n## Breaking changes in v3.x.x\u003c!-- omit from toc --\u003e\n\n- If you have used decimal or Json values you might encounter changed behavior in v3.x.x. Please read the [decimal](#decimal) and [json](#json-null-values) sections for more information. If not you can safely upgrade to v3.x.x.\n- Imports are now generally handled at field level except for model validators. This enables the generator to add the custom validation logic on input type level like `whereUnique` inputs. If you have used custom imports in v2.x.x you should change the syntax to the new one. Please read the [custom imports](#custom-imports) section for more information.\n- `validateWhereUniqueInputs` is now `true` by default\n\n## Known issues and Limitations\u003c!-- omit from toc --\u003e\n\n\u003e - Lowercase model names will result in Errors and duplicate schema names in the generated schemas. Please use uppercase model names and prismas `@@map()` directive when using lowercase table names in the datebase to avoid this issue.\n\u003e - The `satisfies` operator: As some people have pointed out the `input` and `output` schemas and some of the `relation` schemas are typed as `z.ZodType\u003cmyType\u003e`. This is required by zod for recursice types to work properly as [stated in the docs](https://zod.dev/?id=recursive-types). This has the downside that some zod methods like `.merge()`, `.omit()`, etc. are not available on these types.\n\n## Table of contents\u003c!-- omit from toc --\u003e\n\n- [Supported versions](#supported-versions)\n- [About this project](#about-this-project)\n- [Installation](#installation)\n- [`tsconfig.json`](#tsconfigjson)\n- [Usage](#usage)\n  - [`useMultipleFiles`](#usemultiplefiles)\n  - [`output`](#output)\n  - [`writeBarrelFiles`](#writebarrelfiles)\n  - [`createInputTypes`](#createinputtypes)\n  - [`createModelTypes`](#createmodeltypes)\n  - [`addInputTypeValidation`](#addinputtypevalidation)\n  - [`addIncludeType`](#addincludetype)\n  - [`addSelectType`](#addselecttype)\n  - [`validateWhereUniqueInput`](#validatewhereuniqueinput)\n  - [`createOptionalDefaultValuesTypes`](#createoptionaldefaultvaluestypes)\n  - [`createRelationValuesTypes`](#createrelationvaluestypes)\n  - [`createPartialTypes`](#createpartialtypes)\n  - [`useDefaultValidators`](#usedefaultvalidators)\n  - [`coerceDate`](#coercedate)\n  - [`writeNullishInModelTypes`](#writenullishinmodeltypes)\n  - [`useTypeAssertions`](#usetypeassertions)\n  - [`prismaClientPath`](#prismaclientpath)\n- [Skip schema generation](#skip-schema-generation)\n- [Custom Enums](#custom-enums)\n- [Json null values](#json-null-values)\n- [Decimal](#decimal)\n- [Field validators](#field-validators)\n- [Custom type error messages](#custom-type-error-messages)\n- [String validators](#string-validators)\n- [Number validators](#number-validators)\n- [BigInt validators](#bigint-validators)\n- [Date validators](#date-validators)\n- [Custom validators](#custom-validators)\n- [Array validators](#array-validators)\n- [Omit Fields](#omit-fields)\n- [Validation errors](#validation-errors)\n  - [`Wrong zod type`](#wrong-zod-type)\n  - [`Wrong validator`](#wrong-validator)\n  - [`Typo Errors`](#typo-errors)\n- [Model validators](#model-validators)\n- [Custom imports](#custom-imports)\n- [Custom model error messages](#custom-model-error-messages)\n- [Custom model validators](#custom-model-validators)\n- [Naming of zod schemas](#naming-of-zod-schemas)\n- [Adding comments](#adding-comments)\n- [Migration from `zod-prisma`](#migration-from-zod-prisma)\n  - [Generator options](#generator-options)\n    - [`relationModel`](#relationmodel)\n    - [`modelCase`](#modelcase)\n    - [`modelSuffix`](#modelsuffix)\n    - [`useDecimalJs`](#usedecimaljs)\n    - [`imports`](#imports)\n    - [`prismaJsonNullability`](#prismajsonnullability)\n  - [Extending zod fields](#extending-zod-fields)\n  - [Importing helpers](#importing-helpers)\n\n## About this project\n\nFor one of my projects I was in need of a generator that offers the possibility of adding `zod validators` directly in `prisma schema's` [rich-comments](https://www.prisma.io/docs/concepts/components/prisma-schema#comments) and generates `zod` schemas for all prisma models, enums, inputTypes, argTypes, filters and so on. I also wanted to be able to import these schemas in the frontend e.g. for form validation and make the generator as flexible as possible so it covers a large range of use cases. Since there were no generators out there that met my requirements or they weren't actively maintained anymore I decided to write `zod-prisma-type`.\n\n## Installation\n\nvia npm:\n\n```bash\nnpm install zod-prisma-types\n```\n\nvia yarn:\n\n```bash\nyarn add zod-prisma-types\n```\n\nvia pnpm:\n\n```bash\npnpm add zod-prisma-types\n```\n\n## `tsconfig.json`\n\nFor the generator to work properly you have to set the following options in your `tsconfg.json`:\n\n```json\nstrict: true,\nstrictNullChecks: true,\n```\n\n## Usage\n\n\u003e Supports prisma 4.x - 5.x\n\nAdd the following code to your `prisma.schema` file:\n\n```prisma\ngenerator zod {\n  provider       = \"zod-prisma-types\"\n}\n```\n\nThen run the following command to create a single `index.ts` file in the `./generated/zod` output folder containing all the zod prisma schemas:\n\n```sh\nnpx prisma generate zod\n```\n\nThen import the schema's into your file:\n\n```ts\nimport { mySchema } from '/prisma/generated/zod'; // All schemas are here by default, use the 'output' option to change it\n```\n\n\u003e If you encounter errors like the following `/bin/sh: zod-prisma-types: command not found` please try to use the `npx` command with the `zod-prisma-types` command.\n\n```prisma\ngenerator zod {\n  provider       = \"npx zod-prisma-types\"\n}\n```\n\nIf you want to customize the behavior of the generator you can use the following options:\n\n```prisma\ngenerator zod {\n  provider                         = \"ts-node-dev ../generator/src/bin.ts\"\n  output                           = \"./generated/zod\" // default is ./generated/zod\n  useMultipleFiles                 = true // default is false\n  writeBarrelFiles                 = false // default is true\n  createInputTypes                 = false // default is true\n  createModelTypes                 = false // default is true\n  addInputTypeValidation           = false // default is true\n  addIncludeType                   = false // default is true\n  addSelectType                    = false // default is true\n  validateWhereUniqueInput         = false // default is true\n  createOptionalDefaultValuesTypes = true // default is false\n  createRelationValuesTypes        = true // default is false\n  createPartialTypes               = true // default is false\n  useDefaultValidators             = false // default is true\n  coerceDate                       = false // default is true\n  writeNullishInModelTypes         = true // default is false\n  prismaClientPath                 = \"./path/to/prisma/client\" // default is client output path\n}\n```\n\n### `useMultipleFiles`\n\n\u003e default: `false`\n\nIf you want to create multiple files instead of a single `index.ts` file you can set this option to `true`. This will create a file for each model, enum, inputType, argType, filter, etc. The files will be created in sub folders in the specified output folder and a barrel file will be added at the root of the output folder.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  useMultipleFiles = false\n}\n```\n\n### `output`\n\n\u003e default: `./generated/zod`\n\nProvide an alternative output path.\n\n### `writeBarrelFiles`\n\n\u003e default: `true`\n\nIf you use `useMultipleFiles` and do not want to create a barrel file for each sub folder you can set this option to `false`. This will create an `index.ts` file in each sub folder that exports all the files in the folder. This option may be beneficial for typescript performance on big schemas.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  writeBarrelFiles = false\n}\n```\n\n### `createInputTypes`\n\n\u003e default: `true`\n\nIf you just want to create zod schemas for your models and enums you can disable the creation of the corresponding input types. This may be useful if you just want to use zod schemas of your models for validating input types in `react-hook-form` or some similar use cases.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  createInputTypes = false\n}\n```\n\n### `createModelTypes`\n\n\u003e default: `true`\n\nIf you just want to create zod schemas for your input types you can disable the creation of the corresponding model schemas. This may be useful if you just want to use the zod input schemas for autocompletion in your trpc queries or similar use cases.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  createModelTypes = false\n}\n```\n\n### `addInputTypeValidation`\n\n\u003e default: `true`\n\nIf you want to use your custom zod validators that you added via rich-comments only on your generated model schemas but not on your created input type schemas (`UserCreateInput`, `UserUpdateManyInput`, etc.) you can disable this feature.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  addInputTypeValidation = false\n}\n```\n\n### `addIncludeType`\n\n\u003e default: `true`\n\nBy default the include type is added to the `[Model]ArgTypeSchema`. If you don't want to add a zod schema for the `include` type you can set this option to `false`.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  addIncludeType = false\n}\n```\n\n### `addSelectType`\n\n\u003e default: `true`\n\nBy default the select type is added to the `[Model]ArgTypeSchema`. If you don't want to add a zod schema for the `select` type you can set this option to `false`.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  addSelectType = false\n}\n```\n\n### `validateWhereUniqueInput`\n\n\u003e default: `false`\n\nBy default the generator will not validate the `whereUnique` input types in multifile mode since a bunch of unused imports will often be generated. If you want to validate the `whereUnique` input types you can set this option to `true`.\n\n\u003e Be aware that this can lead to eslint errors if you use the `no-unused-vars` rule which you need to resolve manually.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  validateWhereUniqueInput = true\n}\n```\n\n### `createOptionalDefaultValuesTypes`\n\n\u003e default: `false`\n\nIf you want to have a schema of your model where fields with default values are marked as `.optional()` you can pass the following config option:\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  createOptionalDefaultValuesTypes = true\n}\n\nmodel ModelWithDefaultValues {\n  id          Int      @id @default(autoincrement())\n  string      String   @default(\"default\")\n  otherString String\n  int         Int      @default(1)\n  otherInt    Int\n  float       Float    @default(1.1)\n  otherFloat  Float\n  boolean     Boolean  @default(true)\n  otherBool   Boolean\n  date        DateTime @default(now())\n  otherDate   DateTime\n}\n```\n\nThe above model would then generate the following model schemas:\n\n```ts\nexport const ModelWithDefaultValuesSchema = z.object({\n  id: z.number(),\n  string: z.string(),\n  otherString: z.string(),\n  int: z.number(),\n  otherInt: z.number(),\n  float: z.number(),\n  otherFloat: z.number(),\n  boolean: z.boolean(),\n  otherBool: z.boolean(),\n  date: z.date(),\n  otherDate: z.date(),\n});\n\nexport const ModelWithDefaultValuesOptionalDefaultsSchema =\n  ModelWithDefaultValuesSchema.merge(\n    z.object({\n      id: z.number().optional(),\n      string: z.string().optional(),\n      int: z.number().optional(),\n      float: z.number().optional(),\n      boolean: z.boolean().optional(),\n      date: z.date().optional(),\n    }),\n  );\n```\n\n### `createRelationValuesTypes`\n\n\u003e default: `false`\n\nIf you need a separate model type that includes all the relation fields you can pass the following option. Due to the type annotation, that is needed to have recursive types, this model has some limitations since `z.ZodType\u003cmyType\u003e` does not allow some object methods like `.merge()`, `.omit()`, etc.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  createRelationValuesTypes = true\n}\n\nmodel User {\n  id         String      @id @default(cuid())\n  email      String      @unique\n  name       String?\n  posts      Post[]\n  profile    Profile?\n  role       Role[]      @default([USER, ADMIN])\n  enum       AnotherEnum @default(ONE)\n  scalarList String[]\n\n  lat Float\n  lng Float\n\n  location Location? @relation(fields: [lat, lng], references: [lat, lng])\n}\n```\n\nThe above model would generate the following model schemas:\n\n```ts\nexport const UserSchema = z.object({\n  role: RoleSchema.array(),\n  enum: AnotherEnumSchema,\n  id: z.string().cuid(),\n  email: z.string(),\n  name: z.string().optional(),\n  scalarList: z.string().array(),\n  lat: z.number(),\n  lng: z.number(),\n});\n\nexport type UserRelations = {\n  posts: PostWithRelations[];\n  profile?: ProfileWithRelations | null;\n  location?: LocationWithRelations | null;\n};\nexport type UserWithRelations = z.infer\u003ctypeof UserSchema\u003e \u0026 UserRelations;\n\nexport const UserWithRelationsSchema: z.ZodType\u003cUserWithRelations\u003e =\n  UserSchema.merge(\n    z.object({\n      posts: z.lazy(() =\u003e PostWithRelationsSchema).array(),\n      profile: z.lazy(() =\u003e ProfileWithRelationsSchema).nullish(),\n      location: z.lazy(() =\u003e LocationWithRelationsSchema).nullish(),\n    }),\n  );\n```\n\nIf the option is combined with `createOptionalDefaultValuesTypes` additionally the following model schemas are generated:\n\n```ts\nexport type UserOptionalDefaultsWithRelations = z.infer\u003c\n  typeof UserOptionalDefaultsSchema\n\u003e \u0026\n  UserRelations;\n\nexport const UserOptionalDefaultsWithRelationsSchema: z.ZodType\u003cUserOptionalDefaultsWithRelations\u003e =\n  UserOptionalDefaultsSchema.merge(\n    z.object({\n      posts: z.lazy(() =\u003e PostWithRelationsSchema).array(),\n      profile: z.lazy(() =\u003e ProfileWithRelationsSchema).nullable(),\n      location: z.lazy(() =\u003e LocationWithRelationsSchema).nullable(),\n      target: z.lazy(() =\u003e LocationWithRelationsSchema).nullable(),\n    }),\n  );\n```\n\n### `createPartialTypes`\n\n\u003e default: `false`\n\nIf you need a separate model type that includes all the fields as optional you can pass the following option.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  createPartialTypes = true\n}\n\nmodel User {\n  id         String      @id @default(cuid())\n  email      String      @unique\n  name       String?\n  posts      Post[]\n  profile    Profile?\n  role       Role[]      @default([USER, ADMIN])\n  enum       AnotherEnum @default(ONE)\n  scalarList String[]\n\n  lat Float\n  lng Float\n\n  location Location? @relation(fields: [lat, lng], references: [lat, lng])\n}\n```\n\nThe above model would generate the following model schemas:\n\n```ts\nexport const UserPartialSchema = z\n  .object({\n    role: RoleSchema.array(),\n    enum: AnotherEnumSchema,\n    id: z.string().cuid(),\n    email: z.string().email({ message: 'Invalid email address' }),\n    name: z.string().min(1).max(100).nullable(),\n    scalarList: z.string().array(),\n    lat: z.number(),\n    lng: z.number(),\n  })\n  .partial();\n```\n\nWhen using this option in combination with `createRelationValuesTypes` the following model schemas are also generated. Due do the type annotation, that is needed to have recursive types, this model has some limitations since `z.ZodType\u003cmyType\u003e` does not allow some object methods like `.merge()`, `.omit()`, etc.\n\n```ts\nexport type UserPartialRelations = {\n  posts?: PostPartialWithRelations[];\n  profile?: ProfilePartialWithRelations | null;\n  location?: LocationPartialWithRelations | null;\n};\n\nexport type UserPartialWithRelations = z.infer\u003ctypeof UserPartialSchema\u003e \u0026\n  UserPartialRelations;\n\nexport const UserPartialWithRelationsSchema: z.ZodType\u003cUserPartialWithRelations\u003e =\n  UserPartialSchema.merge(\n    z.object({\n      posts: z.lazy(() =\u003e PostPartialWithRelationsSchema).array(),\n      profile: z.lazy(() =\u003e ProfilePartialWithRelationsSchema).nullable(),\n      location: z.lazy(() =\u003e LocationPartialWithRelationsSchema).nullable(),\n    }),\n  ).partial();\n\nexport type UserPartial = z.infer\u003ctypeof UserPartialSchema\u003e;\n```\n\n### `useDefaultValidators`\n\n\u003e default: `true`\n\nIn certain use cases the generator adds default validators:\n\n```prisma\nmodel WithDefaultValidators {\n  id      String @id @default(cuid())\n  idTwo   String @default(uuid())\n  integer Int\n}\n```\n\n```ts\nexport const WithDefaultValidatorsSchema = z.object({\n  id: z.string().cuid(),\n  idTwo: z.string().uuid(),\n  integer: z.number().int(),\n});\n```\n\nThese defaults are overwritten when using a custom validator (see: [Field Validators](#field-validators))\nor when you opt out of using a default validator on a specific field:\n\n```prisma\nmodel WithDefaultValidators {\n  id      String @id @default(cuid()) /// @zod.string.noDefault()\n  idTwo   String @default(uuid()) /// @zod.string.noDefault()\n  integer Int    /// @zod.number.noDefault()\n}\n```\n\n```ts\nexport const WithDefaultValidatorsSchema = z.object({\n  id: z.string(),\n  idTwo: z.string(),\n  integer: z.number(),\n});\n```\n\nYou can opt out of this feature completly by passing false to the config option.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  useDefaultValidators = false\n}\n```\n\n\u003e More default validators are planned in future releases (by checking the @db. fields in the schema). If you have some ideas for default validators feel free to open an issue.\n\n### `coerceDate`\n\n\u003e default: true\n\nPer default `DateTime` values are coerced to `Date` objects as long as you pass in a `valid ISO string` or an `instance of Date`. You can change this behavior to generate a simple `z.date()` by passing the following option to the generator config:\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  coerceDate = false\n}\n```\n\n### `writeNullishInModelTypes`\n\n\u003e default: false\n\nBy default the generator just writes `.nullable()` in the modelTypes when a field in the Prisma type is nullable. If you want these fields to accept `null | undefined`, which would be represented by `.nullish()` in the schema, you can pass the following option to the generator config:\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  writeNullishInModelTypes = true\n}\n```\n\n### `useTypeAssertions`\n\n\u003e default: false\n\nSince there is a known typscript error when using `zod` greater than `3.21.1` you can now use type assertions to circumvent the error and use the latest version of `zod`.\n\n\u003e A WORD OF WARNING: Use this solution at your own risk! Because type assertions are circumventing the type system this can lead to unexpected behavior and runtime errors.\n\u003e But since the types worked in `zod` version `3.21.1` and the error is a known issue in `zod` version `3.21.2` I think it might be a valid solution until the issue is resolved.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  useTypeAssertions = true\n}\n```\n\n### `prismaClientPath`\n\n\u003e default: `inferred from prisma schema path`\n\nBy default the prisma client path is inferred from the `output` path provided in the `prisma.schema` file under `generator client`. If you still need to use a custom path you can pass it to the generator config via this option. A custom path takes precedence over the inferred prisma client output path.\n\n```prisma\ngenerator zod {\n  // ...rest of config\n  prismaClientPath = \"./path/to/prisma/client\"\n}\n```\n\n## Skip schema generation\n\nYou can skip schema generation based on e.g. the environment you are currently working in. For example you can only generate the schemas when you're in `development` but not when you run generation in `production` (because in `production` the schemas would already have been created and pushed to the server via your git repo). To skip generation in an environment just add the following `environment variable` to your respective `.env` files:\n\n```js\nSKIP_ZOD_PRISMA = 'true';\n```\n\n## Custom Enums\n\nFor custom enums a separate type is generated that represents the enum values as a union. Since in typescript unions are more useful than enums this can come in handy.\n\n```prisma\nenum MyEnum {\n  A\n  B\n  C\n}\n```\n\n```ts\nexport const MyEnumSchema = z.nativeEnum(PrismaClient.MyEnum);\n\nexport type MyEnumType = `${z.infer\u003ctypeof MyEnumSchema\u003e}`; // union of \"A\" | \"B\" | \"C\"\n```\n\n## Json null values\n\nWhen using json null values prisma has a unique way of handling Database `NULL` and JSON `null` as stated [in the Docs](https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#using-null-values).\n\nTo adhere to this concept you can pass `\"DbNull\"` or `\"JsonNull\"` as string to a nullable Json field. When the schema gets validated these strings are transformed to `Prisma.DbNull` or `Prisma.JsonNull` to satisfy the `prisma.[myModel].create() | .update() | ...` functions.\n\n\u003e This transformation is only applicable for input schemas like `[myModel]CreateInputSchema, [myModel]UpdateInputSchema, ...`. Since the model schemas represent the return value from the database - they can have `null` values - they are not affected by this transformation.\n\n```ts\nconst parsedJsonSchema = myJsonSchema.parse({\n  myJsonField: 'DbNull', // or \"JsonNull\"\n});\n\n// will be transformed to:\n\nconst parsedJsonSchema = {\n  myJsonField: Prisma.DbNull, // or Prisma.JsonNull\n};\n```\n\n## Decimal\n\nDecimals are a special case since they are not supported by `zod` out of the box. Therefore the generator utilizes the `Prisma.Decimal` class and the `DecimalJsLike` type from the `@prisma/client` package and - if installed - the `decimal.js` package.\n\n\u003e A downside of this approach is that `Prisma` can't be simply imported as a type anymore because it is used to determine if an instance of `Prisma.Decimal` is passed in.\n\nWhen using Decimal a `refine` method is used to validate if the input adheres to the prisma input union `string | number | Decimal | DecimalJsLike`.\n\n```prisma\nmodel MyModel {\n  id      Int     @id @default(autoincrement())\n  decimal Decimal\n}\n```\n\nThe above model would generate the following helper schemas that are used to validate the input in the `create` and `update` methods:\n\n```ts\n// DECIMAL HELPERS\n//------------------------------------------------------\n\nexport const DecimalJSLikeSchema: z.ZodType\u003cPrisma.DecimalJsLike\u003e = z.object({\n  d: z.array(z.number()),\n  e: z.number(),\n  s: z.number(),\n  toFixed: z.function(z.tuple([]), z.string()),\n});\n\nexport const DECIMAL_STRING_REGEX = /^[0-9.,e+-bxffo_cp]+$|Infinity|NaN/;\n\nexport const isValidDecimalInput = (\n  v?: null | string | number | Prisma.DecimalJsLike,\n): v is string | number | Prisma.DecimalJsLike =\u003e {\n  if (v === undefined || v === null) return false;\n  return (\n    (typeof v === 'object' \u0026\u0026\n      'd' in v \u0026\u0026\n      'e' in v \u0026\u0026\n      's' in v \u0026\u0026\n      'toFixed' in v) ||\n    (typeof v === 'string' \u0026\u0026 DECIMAL_STRING_REGEX.test(v)) ||\n    typeof v === 'number'\n  );\n};\n```\n\nThe input schemas reflect the types that are passed to prismas `create` and `update` methods.\nThese schemas further validate the input and throw an error if the input is not valid. A downside of this approach is that Prisma can't be simply imported as a type anymore because it is used to determine if an instance of `Prisma.Decimal` is passed in.\n\n\u003e If `decimal.js` is installed the schema also validates if the input is a valid `decimal.js` instance.\n\n```ts\n// INPUT TYPES\n//------------------------------------------------------\n\nimport { Prisma } from '@prisma/client'; // can't be imported as type because of \"instance of Prisma.Decimal\" check\nimport Decimal from 'decimal.js'; // gets added if installed\nimport { z } from 'zod';\nimport { isValidDecimalInput } from './isValidDecimalInput';\nimport { DecimalJSLikeSchema } from './DecimalJsLikeSchema';\n\nexport const DecimalModelCreateInputSchema: z.ZodType\u003cPrisma.DecimalModelCreateInput\u003e =\n  z\n    .object({\n      decimal: z\n        .union([\n          z.number(),\n          z.string(),\n          z.instanceof(Decimal),\n          z.instanceof(Prisma.Decimal),\n          DecimalJSLikeSchema,\n        ])\n        .refine((v) =\u003e isValidDecimalInput(v), {\n          message: 'Must be a Decimal',\n        }),\n      decimalOpt: z\n        .union([\n          z.number(),\n          z.string(),\n          z.instanceof(Decimal),\n          z.instanceof(Prisma.Decimal),\n          DecimalJSLikeSchema,\n        ])\n        .refine((v) =\u003e isValidDecimalInput(v), { message: 'Must be a Decimal' })\n        .optional()\n        .nullable(),\n    })\n    .strict();\n```\n\nThe model schema only reflects the type of the result of a database query. Therefor this type lacks all the further validation that is used in the `create` and `update` methods. So if you want to validate the input in the `create` and `update` methods you should use the input schemas instead of the model schemas or build your own custom schema using the helpers from above.\n\n```ts\n// SCHEMA\n//------------------------------------------------------\n\nimport { Prisma } from '@prisma/client';\n\nexport const DecimalModelSchema = z.object({\n  id: z.number().int(),\n  decimal: z.instanceof(Prisma.Decimal, {\n    message:\n      \"Field 'decimal' must be a Decimal. Location: ['Models', 'DecimalModel']\",\n  }),\n  decimalOpt: z\n    .instanceof(Prisma.Decimal, {\n      message:\n        \"Field 'decimalOpt' must be a Decimal. Location: ['Models', 'DecimalModel']\",\n    })\n    .nullable(),\n});\n\n// this schema reflects the following prisma type generated in prisma version 5.4.2:\n\nexport type DecimalModel =\n  $Result.DefaultSelection\u003cPrisma.$DecimalModelPayload\u003e;\n\nexport type $DecimalModelPayload\u003c\n  ExtArgs extends $Extensions.InternalArgs = $Extensions.DefaultArgs,\n\u003e = {\n  name: 'DecimalModel';\n  objects: {};\n  scalars: $Extensions.GetPayloadResult\u003c\n    // this part of the type is reflected in the model schema\n    {\n      id: number;\n      decimal: Prisma.Decimal;\n      decimalOpt: Prisma.Decimal | null;\n    },\n    ExtArgs['result']['decimalModel']\n  \u003e;\n  composites: {};\n};\n```\n\n## Field validators\n\nIt is possible to add zod validators in the comments of the `prisma.schema` file with the following syntax (use [rich-comments](https://www.prisma.io/docs/concepts/components/prisma-schema#comments) `///` instead of `//`).\n\n```prisma\nmyField [prisma-scalar-type] /// @zod.[zod-type + optional[(zod-error-messages)]].[zod validators for scalar-type]\n```\n\nThis may look a bit cryptic so here is an example:\n\n```prisma\ngenerator zod {\n  provider       = \"zod-prisma-types\"\n  output         = \"./zod\"\n}\n\n/// @zod.import([\"import { myFunction } from 'mypackage';\"])\nmodel MyPrismaScalarsType {\n  /// @zod.string({ invalid_type_error: \"some error with special chars: some + -*#'substring[]*#!§$%\u0026/{}[]\", required_error: \"some other\", description: \"some description\" }).cuid()\n  id         String    @id @default(cuid())\n  /// Some comment about string @zod.string.min(3, { message: \"min error\" }).max(10, { message: \"max error\" })\n  string     String?\n  /// @zod.custom.use(z.string().refine((val) =\u003e validator.isBIC(val), { message: 'BIC is not valid' }))\n  bic        String?\n  /// @zod.number.lt(10, { message: \"lt error\" }).gt(5, { message: \"gt error\" })\n  float      Float\n  floatOpt   Float?\n  /// @zod.number.int({ message: \"error\" }).gt(5, { message: \"gt error\" })\n  int        Int\n  intOpt     Int?\n  decimal    Decimal\n  decimalOpt Decimal?\n  date       DateTime  @default(now())\n  dateOpt    DateTime? /// @zod.date({ invalid_type_error: \"wrong date type\" })  bigInt     BigInt /// @zod.bigint({ invalid_type_error: \"error\" })\n  bigIntOpt  BigInt?\n  /// @zod.custom.use(z.lazy(() =\u003e InputJsonValue).refine((val) =\u003e myFunction(val), { message: 'Is not valid' }))\n  json       Json\n  jsonOpt    Json?\n  bytes      Bytes /// @zod.custom.use(z.instanceof(Buffer).refine((val) =\u003e val ? true : false, { message: 'Value is not valid' }))\n  bytesOpt   Bytes?\n  /// @zod.custom.use(z.string().refine((val) =\u003e myFunction(val), { message: 'Is not valid' }))\n  custom     String?\n  exclude    String? /// @zod.custom.omit([\"model\", \"input\"])\n\n  updatedAt DateTime @updatedAt\n}\n```\n\nThis example generates the following zod schema for the model in `prisma/zod/index.ts`:\n\n```ts\nimport { z } from 'zod';\nimport * as PrismaClient from '@prisma/client';\nimport validator from 'validator';\nimport { myFunction } from 'mypackage';\n\nexport const MyPrismaScalarsTypeSchema = z.object({\n  id: z\n    .string({\n      invalid_type_error:\n        \"some error with special chars: some + -*#'substring[]*#!§$%\u0026/{}[]\",\n      required_error: 'some other',\n      description: 'some description',\n    })\n    .cuid(),\n  /**\n   * Some comment about string\n   */\n  string: z\n    .string()\n    .min(3, { message: 'min error' })\n    .max(10, { message: 'max error' })\n    .nullish(),\n  bic: z\n    .string()\n    .refine((val) =\u003e validator.isBIC(val), { message: 'BIC is not valid' })\n    .nullish(),\n  float: z\n    .number()\n    .lt(10, { message: 'lt error' })\n    .gt(5, { message: 'gt error' }),\n  floatOpt: z.number().nullish(),\n  int: z.number().int({ message: 'error' }).gt(5, { message: 'gt error' }),\n  intOpt: z.number().int().nullish(),\n  decimal: z\n    .union([\n      z.number(),\n      z.string(),\n      z.instanceof(PrismaClient.Prisma.Decimal),\n      DecimalJSLikeSchema,\n    ])\n    .refine((v) =\u003e isValidDecimalInput(v), {\n      message: 'Field \"decimal\" must be a Decimal',\n      path: ['Models', 'MyPrismaScalarsType'],\n    }),\n  decimalOpt: z\n    .union([\n      z.number(),\n      z.string(),\n      z.instanceof(PrismaClient.Prisma.Decimal),\n      DecimalJSLikeSchema,\n    ])\n    .refine((v) =\u003e isValidDecimalInput(v), {\n      message: 'Field \"decimalOpt\" must be a Decimal',\n      path: ['Models', 'MyPrismaScalarsType'],\n    })\n    .nullish(),\n  date: z.coerce.date(),\n  dateOpt: z.coerce.date({ invalid_type_error: 'wrong date type' }).nullish(),\n  bigIntOpt: z.bigint().nullish(),\n  json: z\n    .lazy(() =\u003e InputJsonValue)\n    .refine((val) =\u003e myFunction(val), { message: 'Is not valid' }),\n  jsonOpt: NullableJsonValue.optional(),\n  bytes: z\n    .instanceof(Buffer)\n    .refine((val) =\u003e (val ? true : false), { message: 'Value is not valid' }),\n  bytesOpt: z.instanceof(Buffer).nullish(),\n  custom: z\n    .string()\n    .refine((val) =\u003e myFunction(val), { message: 'Is not valid' })\n    .nullish(),\n  // omitted: exclude: z.string().nullish(),\n  updatedAt: z.date(),\n});\n\nexport type MyPrismaScalarsType = z.infer\u003ctypeof MyPrismaScalarsTypeSchema\u003e;\n\nexport const MyPrismaScalarsTypeOptionalDefaultsSchema =\n  MyPrismaScalarsTypeSchema.merge(\n    z.object({\n      id: z\n        .string({\n          invalid_type_error:\n            \"some error with special chars: some + -*#'substring[]*#!§$%\u0026/{}[]\",\n          required_error: 'some other',\n          description: 'some description',\n        })\n        .cuid()\n        .optional(),\n      date: z.date().optional(),\n      updatedAt: z.date().optional(),\n    }),\n  );\n```\n\n\u003e Additionally all the zod schemas for the prisma input-, enum-, filter-, orderBy-, select-, include and other necessary types are generated ready to be used in e.g. `trpc` inputs.\n\n## Custom type error messages\n\nTo add custom zod-type error messages to your validator you can add them via `@zod.[key]({ ...customTypeErrorMessages }).[validator key]`. The custom error messages must adhere to the following type:\n\n```ts\ntype RawCreateParams =\n  | {\n      invalid_type_error?: string;\n      required_error?: string;\n      description?: string;\n    }\n  | undefined;\n```\n\nFor example:\n\n```prisma\nmodel MyModel {\n  myField String /// @zod.string({ invalid_type_error: \"invalid type error\", required_error: \"is required\", description: \"describe the error\" })\n}\n```\n\nThis would result in an output like this:\n\n```ts\n string: z.string({\n    invalid_type_error: 'invalid type error',\n    required_error: 'is required',\n    description: 'describe the error',\n  }),\n```\n\nIf you use the wrong key or have a typo the generator will throw an error:\n\n```prisma\nmodel MyModel {\n  myField String  /// @zod.string({ required_error: \"error\", invalid_type_errrrrror: \"error\"})\n}\n```\n\n```bash\n[@zod generator error]: Custom error key 'invalid_type_errrrrror' is not valid. Please check for typos! [Error Location]: Model: 'Test', Field: 'myField'.\n```\n\n## String validators\n\nTo add custom validators to the prisma `String` field you can use the `@zod.string` key. On this key you can use all string-specific validators that are mentioned in the [`zod-docs`](https://github.com/colinhacks/zod#strings). You can also add a custom error message to each validator as stated in the docs.\n\n```prisma\nmodel MyModel {\n  myField String /// @zod.string.min(3, { message: \"min error\" }).max(10, { message: \"max error\" }).[...chain more validators]\n}\n```\n\n## Number validators\n\nTo add custom validators to the prisma `Int` or `Float` field you can use the `@zod.number` key. On this key you can use all number-specific validators that are mentioned in the [`zod-docs`](https://github.com/colinhacks/zod#numbers). You can also add a custom error message to each validator as stated in the docs.\n\n```prisma\nmodel MyModel {\n  myField Int\n/// @zod.number.lt(10, { message: \"lt error\" }).gt(5, { message: \"gt error\" }).[...chain more validators]\n}\n```\n\n## BigInt validators\n\nTo add custom validators to the prisma `BigInt` field you can use the `@zod.bigint` key. On this key you can use all string-specific validators that are mentioned in the [`zod-docs`](https://github.com/colinhacks/zod#bigints). You can also add a custom error message to each validator as stated in the docs.\n\n```prisma\nmodel MyModel {\n  myField BigInt /// @zod.bigint.lt(5n, { message: \"lt error\" }).gt(6n, { message: \"gt error\" })({ invalid_type_error: \"error\", ... }).[...chain more validators]\n}\n```\n\n## Date validators\n\nTo add custom validators to the prisma `DateTime` field you can use the `@zod.date` key. On this key you can use all date-specific validators that are mentioned in the [`zod-docs`](https://github.com/colinhacks/zod#dates). You can also add a custom error message to each validator as stated in the docs.\n\n```prisma\nmodel MyModel {\n  myField DateTime ///  @zod.date.min(new Date('2020-01-01')).max(new Date('2020-12-31'))\n}\n```\n\n## Custom validators\n\nTo add custom validators to any [`Prisma Scalar`](https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#model-field-scalar-types) field you can use the `@zod.custom.use()` key. This key has only the `.use(...your custom code here)` validator. This code overwrites all other standard implementations so you have to specify the `zod type` and how it should be written by the generator. Only `.optional()` and `.nullable()` are added automatically based on your prisma schema type definition. This field is intended to provide validators like zod `.refine` or `.transform` on your fields.\n\n```prisma\nmodel MyModel {\n  id     Int     @id @default(autoincrement())\n  custom String? /// @zod.custom.use(z.string().refine(val =\u003e validator.isBIC(val)).transform(val =\u003e val.toUpperCase()))\n}\n```\n\nThe above model schema would generate the following zod schema:\n\n```ts\nexport const MyModel = z.object({\n  id: z.number(),\n  custom: z\n    .string()\n    .refine((val) =\u003e validator.isBIC(val))\n    .transform((val) =\u003e val.toUpperCase())\n    .nullable(),\n});\n```\n\n## Array validators\n\nTo add custom validators to list fields you can use the `z.[key].array(.length(2).min(1).max(2).nonempty())` validator. You can use this validator on `@zod.string`, `@zod.number`, `@zod.bigint`, `@zod.date` and `@zod.custom`. Furthermore, you can use it on enums with the `@zod.enum.array(...)` key and on relations with the `@zod.object.array(...)` key. You can also add a custom error message to each validator as stated in the docs.\n\n```prisma\nmodel MyModel {\n  id     Int     @id @default(autoincrement())\n  string String[] /// @zod.string.array(.length(2, { message: \"my message\" }).min(1, { message: \"my message\" }).max(2, { message: \"my message\" }).nonempty({ message: \"my message\" }))\n  number Int[] /// @zod.number.array(.length(2).min(1).max(2).nonempty())\n  bigint BigInt[] /// @zod.bigint.array(.length(2).min(1).max(2).nonempty())\n  date   DateTime[] /// @zod.date.array(.length(2).min(1).max(2).nonempty())\n  custom String[] /// @zod.custom.use(z.string().refine(val =\u003e validator.isBIC(val)).transform(val =\u003e val.toUpperCase())).array(.length(2).min(1).max(2).nonempty())\n  enum   MyEnum[] /// @zod.enum.array(.length(2).min(1).max(2).nonempty())\n  object MyObject[] /// @zod.object.array(.length(2).min(1).max(2).nonempty())\n}\n```\n\nThe above model schema would generate the following zod schema:\n\n```ts\nexport const MyModel = z.object({\n  id: z.number(),\n  string: z\n    .string()\n    .array()\n    .length(2, { message: 'my message' })\n    .min(1, { message: 'my message' })\n    .max(2, { message: 'my message' })\n    .nonempty({ message: 'my message' }),\n  number: z.number().array().length(2).min(1).max(2).nonempty(),\n  bigint: z.bigint().array().length(2).min(1).max(2).nonempty(),\n  date: z.date().array().length(2).min(1).max(2).nonempty(),\n  custom: z\n    .string()\n    .refine((val) =\u003e validator.isBIC(val))\n    .transform((val) =\u003e val.toUpperCase())\n    .array()\n    .length(2)\n    .min(1)\n    .max(2)\n    .nonempty(),\n  enum: MyEnumSchema.array().length(2).min(1).max(2).nonempty(),\n});\n```\n\n## Omit Fields\n\nIt is possible to omit fields in the generated zod schemas by using `@zod.custom.omit([\"model\", \"input\"])`. When passing both keys `\"model\"` and `\"input\"` the field is omitted in both, the generated model schema and the generated input types (see example below). If you just want to omit the field in one of the schemas just provide the matching key. You can also write the keys without `\"` or `'`.\n\n```prisma\nmodel MyModel {\n  id           Int     @id @default(autoincrement())\n  string       String? /// @zod.string.min(4).max(10)\n  omitField    String? /// @zod.custom.omit([model, input])\n  omitRequired String /// @zod.custom.omit([model, input])\n}\n```\n\nThe above model would generate the following zod schemas (the omitted keys are left in the model but are commented out so you see at a glance which fields are omitted when looking on the zod schema):\n\n```ts\n// MODEL TYPES\n// ---------------------------------------\n\nexport const MyModelSchema = z.object({\n  id: z.number(),\n  string: z.string().min(4).max(10).nullish(),\n  // omitted: omitField: z.string().nullish(),\n  // omitted: omitRequired: z.string(),\n});\n\n// INPUT TYPES\n// ---------------------------------------\n\nexport const MyModelCreateInputSchema: z.ZodType\u003c\n  Omit\u003cPrismaClient.Prisma.MyModelCreateInput, 'omitField' | 'omitRequired'\u003e\n\u003e = z\n  .object({\n    string: z.string().min(4).max(10).optional().nullable(),\n    // omitted: omitField: z.string().optional().nullable(),\n    // omitted: omitRequired: z.string(),\n  })\n  .strict();\n\nexport const MyModelUncheckedCreateInputSchema: z.ZodType\u003c\n  Omit\u003c\n    PrismaClient.Prisma.MyModelUncheckedCreateInput,\n    'omitField' | 'omitRequired'\n  \u003e\n\u003e = z\n  .object({\n    id: z.number().optional(),\n    string: z.string().min(4).max(10).optional().nullable(),\n    // omitted: omitField: z.string().optional().nullable(),\n    // omitted: omitRequired: z.string(),\n  })\n  .strict();\n\nexport const MyModelUpdateInputSchema: z.ZodType\u003c\n  Omit\u003cPrismaClient.Prisma.MyModelUpdateInput, 'omitField' | 'omitRequired'\u003e\n\u003e = z\n  .object({\n    string: z\n      .union([\n        z.string().min(4).max(10),\n        z.lazy(() =\u003e NullableStringFieldUpdateOperationsInputSchema),\n      ])\n      .optional()\n      .nullable(),\n    // omitted: omitField: z.union([ z.string(),z.lazy(() =\u003e NullableStringFieldUpdateOperationsInputSchema) ]).optional().nullable(),\n    // omitted: omitRequired: z.union([ z.string(),z.lazy(() =\u003e StringFieldUpdateOperationsInputSchema) ]).optional(),\n  })\n  .strict();\n\n// AND SO ON...\n\n// ARG TYPES\n// ---------------------------------------\n\n// To be compatible with the inputTypes the type of the `ArgSchema` is updated accordingly\nexport const MyModelCreateArgsSchema: z.ZodType\u003c\n  Omit\u003cPrismaClient.Prisma.MyModelCreateArgs, 'data'\u003e \u0026 {\n    data:\n      | z.infer\u003ctypeof MyModelCreateInputSchema\u003e\n      | z.infer\u003ctypeof MyModelUncheckedCreateInputSchema\u003e;\n  }\n\u003e = z\n  .object({\n    select: MyModelSelectSchema.optional(),\n    data: z.union([\n      MyModelCreateInputSchema,\n      MyModelUncheckedCreateInputSchema,\n    ]),\n  })\n  .strict();\n```\n\n\u003e When a `required` field is omitted the field needs to be added manually in the respective prisma function like `create`, `update`, `createMany` and so on. Otherwise, Typescript would complain.\n\n```ts\nconst appRouter = t.router({\n  createMyModel: t.procedure\n    .input(MyModelCreateArgsSchema) // field `omitRequired` is not included in `data`\n    .query(({ input }) =\u003e {\n      return prisma.myModel.create({\n        ...input,\n        data: {\n          ...input.data,\n          omitRequired: 'foo', // field needs to be added manually\n        },\n      });\n    }),\n});\n```\n\n## Validation errors\n\nTo ease the developer experience the generator checks if the provided `@zod.[key]` can be used on the respective type of the model field. It also checks if the `@zod.[key].[validator]` can be used on the specified `@zod.[key]`\n\n### `Wrong zod type`\n\nThe generator throws an error if you use a validator key like `@zod.string` on the wrong prisma type.\n\n```prisma\nmodel MyModel {\n  string String /// @zod.string.min(3) -\u003e valid - `string` can be used on `String`\n  number Number /// @zod.string.min(3) -\u003e invalid - `string` can not be used on `Number`\n}\n```\n\nFor the above example the Error message would look like this:\n\n```bash\n[@zod generator error]: Validator 'string' is not valid for type 'Int'. [Error Location]: Model: 'MyModel', Field: 'number'\n```\n\nThe generator provides the exact location, what went wrong and where the error happened. In big prisma schemas with hundreds of models and hundreds of custom validation strings this can come in handy.\n\n### `Wrong validator`\n\nThe generator throws an error if you use a validator `.min` on the wrong validator key.\n\n```prisma\nmodel MyModel {\n  number Int /// @zod.number.min(3) -\u003e invalid - `min` can not be used on `number`\n}\n```\n\nThe above example would throw the following error:\n\n```bash\n[@zod generator error]: Validator 'min' is not valid for type 'Int'. [Error Location]: Model: 'MyModel', Field: 'number'.\n```\n\n### `Typo Errors`\n\nIf you have typos in your validator strings like\n\n```prisma\nmodel MyModel {\n  string String /// @zod.string.min(3, { message: 'Must be at least 3 characters' })\n}\n```\n\nthat the generator would throw the following error:\n\n```bash\n[@zod generator error]: Could not match validator 'min' with validatorPattern\n'.min(3, { mussage: 'Must be at least 3 characters' })'. Please check for typos! [Error Location]: Model: 'MyModel', Field: 'string'.\n```\n\n## Model validators\n\nTo add custom validators to the prisma `model` you can use the `@zod.` key on the model. On this key you can use all [`object`](https://zod.dev/?id=objects) and [`schema`](https://zod.dev/?id=schema-methods) validators that are mentioned in the [`zod-docs`](https://zod.dev/?id=schema-methods).\nYou can also add custom error messages to the object and add custom imports.\n\n```prisma\n/// @zod.import([\"import { myFunction } from \"../../../../utils/myFunction\";\"]).error({ required_error: \"error\", invalid_type_error: \"error\" , description: \"error\"}).refine((data) =\u003e { return true }, { message: \"error\" }).strict()\nmodel ModelWithOptions {\n  id     Int    @id @default(autoincrement())\n  string String\n}\n```\n\nThe above model would generate the following zod schema:\n\n```ts\n/////////////////////////////////////////\n// MODEL WITH OPTIONS SCHEMA\n/////////////////////////////////////////\n\nexport const ModelWithOptionsSchema = z.object(\n  {\n    id: z.number().int(),\n    string: z.string(),\n  },\n  {\n    required_error: 'error',\n    invalid_type_error: 'error',\n    description: 'error',\n  },\n);\n\nexport type ModelWithOptions = z.infer\u003ctypeof ModelWithOptionsSchema\u003e;\n\n/////////////////////////////////////////\n// MODEL WITH OPTIONS CUSTOM VALIDATORS SCHEMA\n/////////////////////////////////////////\n\nexport const ModelWithOptionsCustomValidatorsSchema =\n  ModelWithOptionsSchema.strict().refine(\n    (data) =\u003e {\n      return true;\n    },\n    { message: 'error' },\n  );\n\nexport type ModelWithOptionsCustomValidators = z.infer\u003c\n  typeof ModelWithOptionsCustomValidatorsSchema\n\u003e;\n```\n\n## Custom imports\n\nTo add custom imports to your validator you can add them via `@zod.import([...myCustom imports as strings])` in Prismas rich comments on the model or the field definition.\n\nFor example custom imports on the model level would look like this:\n\n```prisma\n/// @zod.import([\"import { myFunction } from 'mypackage'\"]).refine((val) =\u003e myFunction(val), { message: 'Is not valid' })\nmodel MyModel {\n  myField String /// @zod.string()\n}\n```\n\nThis would result in an output like this:\n\n```ts\nimport { myFunction } from 'mypackage';\n\nexport const MyModelSchema = z\n  .object({\n    myField: z.string(),\n  })\n  .refine((val) =\u003e myFunction(val), { message: 'Is not valid' });\n```\n\nThese custom imports are only used on the generated model schemas and not on the input type schemas.\nIf you want to add custom imports to the generated input type schemas too you can add them to the field definition like this:\n\n```prisma\nmodel ModelWithFieldLevelImport {\n  myField String ///@zod.import([\"import { myFunction } from 'mypackage'\"]).custom.use(z.string().refine((val) =\u003e myFunction(val), { message: 'Is not valid' }))\n}\n```\n\nThis would result in an output like this:\n\n```ts\nimport { myFunction } from 'mypackage';\n\n// MODEL SCHEMA\n// ---------------------------------------\n\nexport const ModelWithFieldLevelImportSchema = z.object({\n  myField: z\n    .string()\n    .refine((val) =\u003e myFunction(val), { message: 'Is not valid' })\n    .optional()\n    .nullable(),\n});\n\n// INPUT SCHEMA\n\nimport { myFunction } from '../../../../utils/myFunction';\n\nexport const ModelWithFieldLevelImportCreateInputSchema: z.ZodType\u003cPrisma.ModelWithFieldLevelImportCreateInput\u003e =\n  z\n    .object({\n      myField: z\n        .string()\n        .refine((val) =\u003e myFunction(val), { message: 'Is not valid' }),\n    })\n    .strict();\n```\n\nWith this approach you can use\n\nThe downside of this approach is that\n\n\u003e Please be aware that you have to add an additional level to relative imports if you use the `useMultipleFiles` option.\n\n## Custom model error messages\n\nTo add custom zod-type error messages to your model schema you can add them via `@zod.error({ ...customTypeErrorMessages })`. The custom error messages must adhere to the following type:\n\n```ts\ntype RawCreateParams =\n  | {\n      invalid_type_error?: string;\n      required_error?: string;\n      description?: string;\n    }\n  | undefined;\n```\n\nFor example:\n\n```prisma\n/// @zod.error({ required_error: \"error\", invalid_type_error: \"error\" , description: \"error\"})\nmodel MyModel {\n  myField String\n}\n```\n\nThis would result in an output like this:\n\n```ts\nexport const MyModelSchema = z.object(\n  {\n    myField: z.string(),\n  },\n  {\n    required_error: 'error',\n    invalid_type_error: 'error',\n    description: 'error',\n  },\n);\n```\n\n## Custom model validators\n\nTo add custom validators to the prisma `model` you can use the `@zod.` key on the model. On this key you can use all [`object`](https://zod.dev/?id=objects) and [`schema`](https://zod.dev/?id=schema-methods) validators that are mentioned in the [`zod-docs`](https://zod.dev/?id=schema-methods).\n\n```prisma\n/// @zod.refine((data) =\u003e { return true }, { message: \"error\" }).strict()\nmodel ModelWithOptions {\n  id     Int    @id @default(autoincrement())\n  string String\n}\n```\n\nThe above model would generate the following zod schema:\n\n```ts\n/////////////////////////////////////////\n// MODEL WITH OPTIONS SCHEMA\n/////////////////////////////////////////\n\nexport const ModelWithOptionsSchema = z.object({\n  id: z.number().int(),\n  string: z.string(),\n});\n\nexport type ModelWithOptions = z.infer\u003ctypeof ModelWithOptionsSchema\u003e;\n\n/////////////////////////////////////////\n// MODEL WITH OPTIONS CUSTOM VALIDATORS SCHEMA\n/////////////////////////////////////////\n\nexport const ModelWithOptionsCustomValidatorsSchema =\n  ModelWithOptionsSchema.strict().refine(\n    (data) =\u003e {\n      return true;\n    },\n    { message: 'error' },\n  );\n\nexport type ModelWithOptionsCustomValidators = z.infer\u003c\n  typeof ModelWithOptionsCustomValidatorsSchema\n\u003e;\n```\n\n\u003e If strict is passed in it is always added to the model schema at the first position. All other validators are added in the order they appear in the rich comments.\n\n## Naming of zod schemas\n\nThe zod types are named after the generated prisma types with an appended `\"Schema\"` string. You just need to hover over a prisma function and you know which type to import. This would look something like this for trpc v.10:\n\n```ts\nimport {\n  UserFindFirstArgsSchema,\n  UserFindManyArgsSchema,\n  UserFindUniqueArgsSchema,\n} from './prisma/zod';\n\nconst appRouter = t.router({\n  findManyUser: t.procedure.input(UserFindManyArgsSchema).query(({ input }) =\u003e {\n    return prisma.user.findMany(input);\n  }),\n  findUniqueUser: t.procedure\n    .input(UserFindUniqueArgsSchema)\n    .query(({ input }) =\u003e {\n      return prisma.user.findUnique(input);\n    }),\n\n  findFirstUser: t.procedure\n    .input(UserFindFirstArgsSchema)\n    .query(({ input }) =\u003e {\n      return prisma.user.findFirst(input);\n    }),\n});\n```\n\n## Adding comments\n\nYou can add [rich-comments](https://www.prisma.io/docs/concepts/components/prisma-schema#comments) to your models and fields that are then printed as jsDoc in your generated zod schema.\n\n```prisma\n/// comment line one\n/// comment line two\nmodel MyModel {\n  id     Int     @id @default(autoincrement())\n  /// comment before validator @zod.string.min(4).max(10)\n  /// comment after validator\n  string String?\n}\n```\n\nThe above model would generate the following output where the validator is extracted from the rich comments and added to the string field:\n\n```ts\n/**\n * comment line one\n * comment line two\n */\nexport const MyModelSchema = z.object({\n  id: z.number(),\n  /**\n   * comment before validator\n   * comment after validator\n   */\n  string: z.string().min(4).max(10).nullish(),\n});\n```\n\nThe validator is extracted from the comments and added to the string\n\n## Migration from `zod-prisma`\n\nThere are a few differences between `zod-prisma` and `zod-prisma-types`.\nThe following sections should help you migrate from `zod-prisma` to `zod-prisma-types`.\n\n### Generator options\n\nThe following generator options from `zod-prisma` are not supported or implemented differently by `zod-prisma-types`:\n\n#### `relationModel`\n\nYou can generate a schema that contains all relations of a model by passing the following option to the generator:\n\n```prisma\ngenerator zod {\n  // ... other options\n  createRelationValuesTypes = true\n}\n```\n\nSee [`createRelationValuesTypes`](#createrelationvaluestypes) for more information.\n\n#### `modelCase`\n\nThe casing of the model is fixed to the casing used in the `prisma schema` and can not be changed. This way model names with mixed casing like `MYModel` will work as expected when generating `inputTypes`, `enums`, `argTypes`, etc.\n\n#### `modelSuffix`\n\nThe model suffix in `zod-prisma-types` is fixed to `Schema` and can not be changed.\n\n#### `useDecimalJs`\n\n`zod-prisma-types` does not support `decimal.js` but uses the decimal implementation provided by prisma to validate Decimal types. See [Decimal](#decimal) for more information.\n\n#### `imports`\n\nAs of version `2.0.0` imports in `zod-prisma-types` are handled with rich-comments on the model definition. See [Custom imports](#custom-imports) for more information.\n\n#### `prismaJsonNullability`\n\nThe nullablility in `zod-prisma-types` is handled differently. See [Json null values](#json-null-values) for more information.\n\n### Extending zod fields\n\n`zod-prisma` allows you to extend the zod fields with custom validators. This is also possible with `zod-prisma-types` and the `@zod.[key].[validator]` syntax. The different syntax is used to check if a validator can be used on a specific prisma type. See [Field validators](#field-validators) for more information.\n\n```prisma\n\n// zod-prisma\nmodel MyModel {\n  string String /// @zod.min(3) -\u003e valid - `string` can be used on `String`\n  number Number /// @zod.min(3) -\u003e valid - throws error only at runtime\n}\n\n//zod-prisma-types\nmodel MyModel {\n  string String /// @zod.string.min(3) -\u003e valid - `string` can be used on `String`\n  number Number /// @zod.string.min(3) -\u003e invalid - throws error during generation\n}\n```\n\n### Importing helpers\n\nYou can import custom helpers in the generator. Please refer to the section about [custom imports](#custom-imports) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchrishoermann%2Fzod-prisma-types","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchrishoermann%2Fzod-prisma-types","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchrishoermann%2Fzod-prisma-types/lists"}