zod 3.25.0-canary.20250211T214501 โ†’ 4.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/commonjs/checks.d.ts +1 -0
  2. package/dist/commonjs/checks.js +32 -0
  3. package/dist/commonjs/coerce.d.ts +17 -0
  4. package/dist/commonjs/coerce.js +57 -0
  5. package/dist/commonjs/compat.d.ts +47 -0
  6. package/dist/commonjs/compat.js +73 -0
  7. package/dist/commonjs/errors.d.ts +23 -0
  8. package/dist/commonjs/errors.js +57 -0
  9. package/dist/commonjs/external.d.ts +8 -0
  10. package/dist/commonjs/external.js +67 -0
  11. package/dist/commonjs/index.d.ts +4 -0
  12. package/{lib โ†’ dist/commonjs}/index.js +19 -9
  13. package/dist/commonjs/iso.d.ts +22 -0
  14. package/dist/commonjs/iso.js +70 -0
  15. package/dist/commonjs/package.json +3 -0
  16. package/dist/commonjs/parse.d.ts +17 -0
  17. package/dist/commonjs/parse.js +44 -0
  18. package/dist/commonjs/schemas.d.ts +738 -0
  19. package/dist/commonjs/schemas.js +1171 -0
  20. package/dist/esm/checks.d.ts +1 -0
  21. package/dist/esm/checks.js +1 -0
  22. package/dist/esm/coerce.d.ts +17 -0
  23. package/dist/esm/coerce.js +17 -0
  24. package/dist/esm/compat.d.ts +47 -0
  25. package/dist/esm/compat.js +33 -0
  26. package/dist/esm/errors.d.ts +23 -0
  27. package/dist/esm/errors.js +20 -0
  28. package/dist/esm/external.d.ts +8 -0
  29. package/dist/esm/external.js +11 -0
  30. package/dist/esm/index.d.ts +4 -0
  31. package/dist/esm/index.js +4 -0
  32. package/dist/esm/iso.d.ts +22 -0
  33. package/dist/esm/iso.js +30 -0
  34. package/dist/esm/package.json +3 -0
  35. package/dist/esm/parse.d.ts +17 -0
  36. package/dist/esm/parse.js +8 -0
  37. package/dist/esm/schemas.d.ts +738 -0
  38. package/dist/esm/schemas.js +1057 -0
  39. package/package.json +59 -99
  40. package/src/checks.ts +30 -0
  41. package/src/coerce.ts +27 -0
  42. package/src/compat.ts +74 -0
  43. package/src/errors.ts +47 -0
  44. package/src/external.ts +29 -0
  45. package/src/index.ts +5 -0
  46. package/src/iso.ts +90 -0
  47. package/src/parse.ts +32 -0
  48. package/src/schemas.ts +2324 -0
  49. package/README.md +0 -3074
  50. package/index.d.ts +0 -2
  51. package/lib/ZodError.d.ts +0 -164
  52. package/lib/ZodError.js +0 -137
  53. package/lib/__tests__/Mocker.d.ts +0 -17
  54. package/lib/__tests__/Mocker.js +0 -57
  55. package/lib/benchmarks/datetime.d.ts +0 -5
  56. package/lib/benchmarks/datetime.js +0 -54
  57. package/lib/benchmarks/discriminatedUnion.d.ts +0 -5
  58. package/lib/benchmarks/discriminatedUnion.js +0 -79
  59. package/lib/benchmarks/index.d.ts +0 -1
  60. package/lib/benchmarks/index.js +0 -59
  61. package/lib/benchmarks/ipv4.d.ts +0 -5
  62. package/lib/benchmarks/ipv4.js +0 -54
  63. package/lib/benchmarks/object.d.ts +0 -5
  64. package/lib/benchmarks/object.js +0 -70
  65. package/lib/benchmarks/primitives.d.ts +0 -5
  66. package/lib/benchmarks/primitives.js +0 -170
  67. package/lib/benchmarks/realworld.d.ts +0 -5
  68. package/lib/benchmarks/realworld.js +0 -56
  69. package/lib/benchmarks/string.d.ts +0 -5
  70. package/lib/benchmarks/string.js +0 -55
  71. package/lib/benchmarks/union.d.ts +0 -5
  72. package/lib/benchmarks/union.js +0 -79
  73. package/lib/errors.d.ts +0 -5
  74. package/lib/errors.js +0 -17
  75. package/lib/external.d.ts +0 -6
  76. package/lib/external.js +0 -22
  77. package/lib/helpers/enumUtil.d.ts +0 -8
  78. package/lib/helpers/enumUtil.js +0 -2
  79. package/lib/helpers/errorUtil.d.ts +0 -9
  80. package/lib/helpers/errorUtil.js +0 -8
  81. package/lib/helpers/parseUtil.d.ts +0 -78
  82. package/lib/helpers/parseUtil.js +0 -125
  83. package/lib/helpers/partialUtil.d.ts +0 -8
  84. package/lib/helpers/partialUtil.js +0 -2
  85. package/lib/helpers/typeAliases.d.ts +0 -2
  86. package/lib/helpers/typeAliases.js +0 -2
  87. package/lib/helpers/util.d.ts +0 -82
  88. package/lib/helpers/util.js +0 -142
  89. package/lib/index.d.ts +0 -4
  90. package/lib/index.mjs +0 -4405
  91. package/lib/index.umd.js +0 -4520
  92. package/lib/locales/en.d.ts +0 -3
  93. package/lib/locales/en.js +0 -129
  94. package/lib/standard-schema.d.ts +0 -102
  95. package/lib/standard-schema.js +0 -2
  96. package/lib/types.d.ts +0 -1062
  97. package/lib/types.js +0 -3846
package/README.md DELETED
@@ -1,3074 +0,0 @@
1
- <p align="center">
2
- <img src="logo.svg" width="200px" align="center" alt="Zod logo" />
3
- <h1 align="center">Zod</h1>
4
- <p align="center">
5
- โœจ <a href="https://zod.dev">https://zod.dev</a> โœจ
6
- <br/>
7
- TypeScript-first schema validation with static type inference
8
- </p>
9
- </p>
10
- <br/>
11
- <p align="center">
12
- <a href="https://github.com/colinhacks/zod/actions?query=branch%3Amain"><img src="https://github.com/colinhacks/zod/actions/workflows/test.yml/badge.svg?event=push&branch=main" alt="Zod CI status" /></a>
13
- <a href="https://twitter.com/colinhacks" rel="nofollow"><img src="https://img.shields.io/badge/created%20by-@colinhacks-4BBAAB.svg" alt="Created by Colin McDonnell"></a>
14
- <a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/colinhacks/zod" alt="License"></a>
15
- <a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/npm/dw/zod.svg" alt="npm"></a>
16
- <a href="https://github.com/colinhacks/zod" rel="nofollow"><img src="https://img.shields.io/github/stars/colinhacks/zod" alt="stars"></a>
17
- </p>
18
-
19
- <div align="center">
20
- <a href="https://zod.dev">Documentation</a>
21
- <span>&nbsp;&nbsp;โ€ข&nbsp;&nbsp;</span>
22
- <a href="https://discord.gg/RcG33DQJdf">Discord</a>
23
- <span>&nbsp;&nbsp;โ€ข&nbsp;&nbsp;</span>
24
- <a href="https://www.npmjs.com/package/zod">npm</a>
25
- <span>&nbsp;&nbsp;โ€ข&nbsp;&nbsp;</span>
26
- <a href="https://deno.land/x/zod">deno</a>
27
- <span>&nbsp;&nbsp;โ€ข&nbsp;&nbsp;</span>
28
- <a href="https://github.com/colinhacks/zod/issues/new">Issues</a>
29
- <span>&nbsp;&nbsp;โ€ข&nbsp;&nbsp;</span>
30
- <a href="https://twitter.com/colinhacks">@colinhacks</a>
31
- <span>&nbsp;&nbsp;โ€ข&nbsp;&nbsp;</span>
32
- <a href="https://trpc.io">tRPC</a>
33
- <br />
34
- </div>
35
-
36
- <br/>
37
- <br/>
38
-
39
- <!-- <p><strong>Announcement โœจ</strong> Zod has recieved the <a href="https://go.clerk.com/zod-clerk">Clerk</a> OSS Fellowship!<br/>Read the announcement post ๐Ÿ‘‰ <a href="https://go.clerk.com/zod-clerk">clerk.com/blog/zod-fellowship</a></p> -->
40
-
41
- [![clerk announcement](https://github.com/colinhacks/zod/assets/3084745/6327cf99-8d82-4b44-a5b1-ba2b5c2ff6ad)](https://go.clerk.com/hqN4rp7)
42
-
43
- <br/>
44
-
45
- ## Table of contents
46
-
47
- > These docs have been translated into [Chinese](./README_ZH.md) and [Korean](./README_KO.md).
48
-
49
- - [Table of contents](#table-of-contents)
50
- - [Introduction](#introduction)
51
- - [Sponsors](#sponsors)
52
- - [Platinum](#platinum)
53
- - [Gold](#gold)
54
- - [Silver](#silver)
55
- - [Bronze](#bronze)
56
- - [Copper](#copper)
57
- - [Ecosystem](#ecosystem)
58
- - [Resources](#resources)
59
- - [API libraries](#api-libraries)
60
- - [Form integrations](#form-integrations)
61
- - [Zod to X](#zod-to-x)
62
- - [X to Zod](#x-to-zod)
63
- - [Mocking](#mocking)
64
- - [Powered by Zod](#powered-by-zod)
65
- - [Utilities for Zod](#utilities-for-zod)
66
- - [Installation](#installation)
67
- - [Requirements](#requirements)
68
- - [From `npm`](#from-npm)
69
- - [Basic usage](#basic-usage)
70
- - [Primitives](#primitives)
71
- - [Coercion for primitives](#coercion-for-primitives)
72
- - [Literals](#literals)
73
- - [Strings](#strings)
74
- - [Datetimes](#datetimes)
75
- - [Dates](#dates)
76
- - [Times](#times)
77
- - [IP addresses](#ip-addresses)
78
- - [IP ranges](#ip-ranges-cidr)
79
- - [Numbers](#numbers)
80
- - [BigInts](#bigints)
81
- - [NaNs](#nans)
82
- - [Booleans](#booleans)
83
- - [Dates](#dates-1)
84
- - [Zod enums](#zod-enums)
85
- - [Native enums](#native-enums)
86
- - [Optionals](#optionals)
87
- - [Nullables](#nullables)
88
- - [Objects](#objects)
89
- - [`.shape`](#shape)
90
- - [`.keyof`](#keyof)
91
- - [`.extend`](#extend)
92
- - [`.merge`](#merge)
93
- - [`.pick/.omit`](#pickomit)
94
- - [`.partial`](#partial)
95
- - [`.deepPartial`](#deeppartial)
96
- - [`.required`](#required)
97
- - [`.passthrough`](#passthrough)
98
- - [`.strict`](#strict)
99
- - [`.strip`](#strip)
100
- - [`.catchall`](#catchall)
101
- - [Arrays](#arrays)
102
- - [`.element`](#element)
103
- - [`.nonempty`](#nonempty)
104
- - [`.min/.max/.length`](#minmaxlength)
105
- - [Tuples](#tuples)
106
- - [Unions](#unions)
107
- - [Discriminated unions](#discriminated-unions)
108
- - [Records](#records)
109
- - [Record key type](#record-key-type)
110
- - [Maps](#maps)
111
- - [Sets](#sets)
112
- - [Intersections](#intersections)
113
- - [Recursive types](#recursive-types)
114
- - [ZodType with ZodEffects](#zodtype-with-zodeffects)
115
- - [JSON type](#json-type)
116
- - [Cyclical objects](#cyclical-objects)
117
- - [Promises](#promises)
118
- - [Instanceof](#instanceof)
119
- - [Functions](#functions)
120
- - [Preprocess](#preprocess)
121
- - [Custom schemas](#custom-schemas)
122
- - [Schema methods](#schema-methods)
123
- - [`.parse`](#parse)
124
- - [`.parseAsync`](#parseasync)
125
- - [`.safeParse`](#safeparse)
126
- - [`.safeParseAsync`](#safeparseasync)
127
- - [`.refine`](#refine)
128
- - [Arguments](#arguments)
129
- - [Customize error path](#customize-error-path)
130
- - [Asynchronous refinements](#asynchronous-refinements)
131
- - [Relationship to transforms](#relationship-to-transforms)
132
- - [`.superRefine`](#superrefine)
133
- - [Abort early](#abort-early)
134
- - [Type refinements](#type-refinements)
135
- - [`.transform`](#transform)
136
- - [Chaining order](#chaining-order)
137
- - [Validating during transform](#validating-during-transform)
138
- - [Relationship to refinements](#relationship-to-refinements)
139
- - [Async transforms](#async-transforms)
140
- - [`.default`](#default)
141
- - [`.describe`](#describe)
142
- - [`.catch`](#catch)
143
- - [`.optional`](#optional)
144
- - [`.nullable`](#nullable)
145
- - [`.nullish`](#nullish)
146
- - [`.array`](#array)
147
- - [`.promise`](#promise)
148
- - [`.or`](#or)
149
- - [`.and`](#and)
150
- - [`.brand`](#brand)
151
- - [`.readonly`](#readonly)
152
- - [`.pipe`](#pipe)
153
- - [You can use `.pipe()` to fix common issues with `z.coerce`.](#you-can-use-pipe-to-fix-common-issues-with-zcoerce)
154
- - [Guides and concepts](#guides-and-concepts)
155
- - [Type inference](#type-inference)
156
- - [Writing generic functions](#writing-generic-functions)
157
- - [Constraining allowable inputs](#constraining-allowable-inputs)
158
- - [Error handling](#error-handling)
159
- - [Error formatting](#error-formatting)
160
- - [Comparison](#comparison)
161
- - [Joi](#joi)
162
- - [Yup](#yup)
163
- - [io-ts](#io-ts)
164
- - [Runtypes](#runtypes)
165
- - [Ow](#ow)
166
- - [Changelog](#changelog)
167
-
168
- ## Introduction
169
-
170
- Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple `string` to a complex nested object.
171
-
172
- Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator _once_ and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures.
173
-
174
- Some other great aspects:
175
-
176
- - Zero dependencies
177
- - Works in Node.js and all modern browsers
178
- - Tiny: 8kb minified + zipped
179
- - Immutable: methods (e.g. `.optional()`) return a new instance
180
- - Concise, chainable interface
181
- - Functional approach: [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)
182
- - Works with plain JavaScript too! You don't need to use TypeScript.
183
-
184
- ## Sponsors
185
-
186
- Sponsorship at any level is appreciated and encouraged. If you built a paid product using Zod, consider one of the [corporate tiers](https://github.com/sponsors/colinhacks).
187
-
188
- <br/>
189
- <h3 align="center">Diamond</h3>
190
-
191
- <br/>
192
-
193
- <div align="center">
194
- <a href="https://go.clerk.com/PKHrcwh">
195
- <picture width="100%">
196
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/colinhacks/zod/assets/3084745/15c8c8be-189d-44ed-b3db-59bf2a21cbe3">
197
- <img alt="clerk logo" src="https://github.com/colinhacks/zod/assets/3084745/15c8c8be-189d-44ed-b3db-59bf2a21cbe3">
198
- </picture>
199
- </a>
200
- <br/>
201
- <br/>
202
- <p>
203
- The most comprehensive User Management Platform
204
- <br/>
205
- <a style="text-decoration:none;" href="https://go.clerk.com/PKHrcwh" target="_blank">clerk.com</a>
206
- </p>
207
- </div>
208
-
209
- <br/>
210
- <br/>
211
-
212
- <h3 align="center">Platinum</h3>
213
-
214
- <table align="center" style="justify-content: center;align-items: center;display: flex;">
215
- <tr>
216
- <td align="center">
217
- <p></p>
218
- <p>
219
- <a href="https://www.coderabbit.ai/">
220
- <picture height="80px">
221
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/eea24edb-ff20-4532-b57c-e8719f455d6d">
222
- <img alt="CodeRabbit logo" height="80px" src="https://github.com/user-attachments/assets/d791bc7d-dc60-4d55-9c31-97779839cb74">
223
- </picture>
224
- </a>
225
- <br />
226
- Cut code review time & bugs in half
227
- <br/>
228
- <a href="https://www.coderabbit.ai/" style="text-decoration:none;">coderabbit.ai</a>
229
- </p>
230
- <p></p>
231
- </td>
232
- </tr>
233
- </table>
234
-
235
- <br/>
236
-
237
- <h3 align="center">Gold</h3>
238
-
239
- <table align="center" style="justify-content: center;align-items: center;display: flex;">
240
- <tr>
241
- <td align="center">
242
- <p></p>
243
- <p>
244
- <a href="https://www.courier.com/?utm_source=zod&utm_campaign=osssponsors">
245
- <picture height="62px">
246
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/6b09506a-78de-47e8-a8c1-792efe31910a">
247
- <img alt="Courier logo" height="62px" src="https://github.com/user-attachments/assets/6b09506a-78de-47e8-a8c1-792efe31910a">
248
- </picture>
249
- </a>
250
- <br />
251
- The API platform for sending notifications
252
- <br/>
253
- <a href="https://www.courier.com/?utm_source=zod&utm_campaign=osssponsors" style="text-decoration:none;">courier.com</a>
254
- </p>
255
- <p></p>
256
- </td>
257
- <td align="center">
258
- <p></p>
259
- <p>
260
- <a href="https://liblab.com/?utm_source=zod">
261
- <picture height="62px">
262
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/34dfa1a2-ce94-46f4-8902-fbfac3e1a9bc">
263
- <img alt="LibLab" height="62px" src="https://github.com/user-attachments/assets/3de0b617-5137-49c4-b72d-a033cbe602d8">
264
- </picture>
265
- </a>
266
- <br />
267
- Generate better SDKs for your APIs
268
- <br/>
269
- <a href="https://liblab.com/?utm_source=zod" style="text-decoration:none;">liblab.com</a>
270
- </p>
271
- <p></p>
272
- </td>
273
- </tr>
274
- <tr>
275
- <td align="center">
276
- <p></p>
277
- <p>
278
- <a href="https://neon.tech">
279
- <picture height="68px">
280
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/83b4b1b1-a9ab-4ae5-a632-56d282f0c444">
281
- <img alt="Neon" height="68px" src="https://github.com/user-attachments/assets/b5799fc8-81ff-4053-a1c3-b29adf85e7a1">
282
- </picture>
283
- </a>
284
- <br />
285
- Serverless Postgres โ€” Ship faster
286
- <br/>
287
- <a href="https://neon.tech" style="text-decoration:none;">neon.tech</a>
288
- </p>
289
- <p></p>
290
- </td>
291
- <td align="center">
292
- <p></p>
293
- <p>
294
- <a href="https://retool.com/?utm_source=github&utm_medium=referral&utm_campaign=zod">
295
- <picture height="45px">
296
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/colinhacks/zod/assets/3084745/ac65013f-aeb4-48dd-a2ee-41040b69cbe6">
297
- <img alt="stainless" height="45px" src="https://github.com/colinhacks/zod/assets/3084745/5ef4c11b-efeb-4495-90a8-41b83f798600">
298
- </picture>
299
- </a>
300
- <br />
301
- Build AI apps and workflows with <a href="https://retool.com/products/ai?utm_source=github&utm_medium=referral&utm_campaign=zod">Retool AI</a>
302
- <br/>
303
- <a href="https://retool.com/?utm_source=github&utm_medium=referral&utm_campaign=zod" style="text-decoration:none;">retool.com</a>
304
- </p>
305
- <p></p>
306
- </td>
307
- </tr>
308
- <tr>
309
- <td align="center">
310
- <p></p>
311
- <p>
312
- <a href="https://stainlessapi.com">
313
- <picture height="45px">
314
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/colinhacks/zod/assets/3084745/f20759c1-3e51-49d0-a31e-bbc43abec665">
315
- <img alt="stainless" height="45px" src="https://github.com/colinhacks/zod/assets/3084745/e9444e44-d991-4bba-a697-dbcfad608e47">
316
- </picture>
317
- </a>
318
- <br />
319
- Generate best-in-class SDKs
320
- <br/>
321
- <a href="https://stainlessapi.com" style="text-decoration:none;">stainlessapi.com</a>
322
- </p>
323
- <p></p>
324
- </td>
325
- <td align="center">
326
- <p></p>
327
- <p>
328
- <a href="https://speakeasy.com/?utm_source=zod+docs">
329
- <picture height="40px">
330
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/colinhacks/zod/assets/3084745/b1d86601-c7fb-483c-9927-5dc24ce8b737">
331
- <img alt="speakeasy" height="40px" src="https://github.com/colinhacks/zod/assets/3084745/647524a4-22bb-4199-be70-404207a5a2b5">
332
- </picture>
333
- </a>
334
- <br />
335
- SDKs & Terraform providers for your API
336
- <br/>
337
- <a href="https://speakeasy.com/?utm_source=zod+docs" style="text-decoration:none;">speakeasy.com</a>
338
- </p>
339
- <p></p>
340
- </td>
341
- </tr>
342
- </table>
343
-
344
- <br/>
345
-
346
- <h3 align="center">Silver</h3>
347
-
348
- <table align="center" style="justify-content: center;align-items: center;display: flex;">
349
- <tr>
350
- <td align="center">
351
- <img src="https://avatars.githubusercontent.com/u/72055470?s=200&v=4" height="50px;" alt="Nitric" />
352
- <br />
353
- <a style="text-decoration:none;" href="https://nitric.io/" target="_blank">Nitric</a>
354
- </td>
355
- <td align="center">
356
- <img src="https://avatars.githubusercontent.com/u/89474619?s=200&v=4" height="50px;" alt="PropelAuth" />
357
- <br />
358
- <a style="text-decoration:none;" href="https://www.propelauth.com/" target="_blank">PropelAuth</a>
359
- </td>
360
- <td align="center">
361
- <img src="https://avatars.githubusercontent.com/u/80861386?s=200&v=4" height="50px;" alt="Cerbos" />
362
- <br />
363
- <a style="text-decoration:none;" href="https://cerbos.dev/" target="_blank">Cerbos</a>
364
- </td>
365
- <td align="center">
366
- <img src="https://avatars.githubusercontent.com/u/301879?s=200&v=4" height="50px;" alt="Scalar.com logo" />
367
- <br />
368
- <a style="text-decoration:none;" href="https://scalar.com/" target="_blank">Scalar</a>
369
- </td>
370
- </tr><tr>
371
- <td align="center">
372
- <img src="https://avatars.githubusercontent.com/u/95297378?s=200&v=4" height="50px;" alt="Trigger.dev logo" />
373
- <br />
374
- <a style="text-decoration:none;" href="https://trigger.dev" target="_blank">Trigger.dev</a>
375
- </td>
376
- <td align="center">
377
- <img src="https://avatars.githubusercontent.com/u/125754?s=200&v=4" height="50px;" alt="Transloadit logo" />
378
- <br />
379
- <a style="text-decoration:none;" href="https://transloadit.com/?utm_source=zod&utm_medium=refe
380
- rral&utm_campaign=sponsorship&utm_content=github" target="_blank">Transloadit</a>
381
- </td>
382
- <td align="center">
383
- <img src="https://avatars.githubusercontent.com/u/107880645?s=200&v=4" height="50px;" alt="Infisical logo" />
384
- <br />
385
- <a style="text-decoration:none;" href="https://infisical.com" target="_blank">Infisical</a>
386
- </td>
387
- <td align="center">
388
- <img src="https://avatars.githubusercontent.com/u/91036480?s=200&v=4" height="50px;" alt="Whop logo" />
389
- <br />
390
- <a style="text-decoration:none;" href="https://whop.com/" target="_blank">Whop</a>
391
- </td>
392
- </tr><tr>
393
- <td align="center">
394
- <img src="https://avatars.githubusercontent.com/u/36402888?s=200&v=4" height="50px;" alt="CryptoJobsList logo" />
395
- <br />
396
- <a style="text-decoration:none;" href="https://cryptojobslist.com/" target="_blank">CryptoJobsList</a>
397
- </td>
398
- <td align="center">
399
- <img src="https://avatars.githubusercontent.com/u/70170949?s=200&v=4" height="50px;" alt="Plain logo" />
400
- <br />
401
- <a style="text-decoration:none;" href="https://plain.com/" target="_blank">Plain.</a>
402
- </td>
403
- <td align="center">
404
- <img src="https://avatars.githubusercontent.com/u/78935958?s=200&v=4" height="50px;" alt="Inngest logo" />
405
- <br />
406
- <a style="text-decoration:none;" href="https://inngest.com/" target="_blank">Inngest</a>
407
- </td>
408
- <td align="center">
409
- <img src="https://avatars.githubusercontent.com/u/13880908?s=200&v=4" height="50px;" alt="Storyblok CMS" />
410
- <br />
411
- <a style="text-decoration:none;" href="https://storyblok.com/" target="_blank">Storyblok</a>
412
- </td>
413
- </tr><tr>
414
- <td align="center">
415
- <img src="https://avatars.githubusercontent.com/u/16199997?s=200&v=4" height="50px;" alt="Mux logo" />
416
- <br />
417
- <a style="text-decoration:none;" href="https://mux.link/zod" target="_blank">Mux</a>
418
- </td>
419
- </tr>
420
- </table>
421
-
422
- <br/>
423
-
424
- <h3 align="center">Bronze</h3>
425
-
426
- <table align="center" style="justify-content: center;align-items: center;display: flex;">
427
- <tr>
428
- <td align="center">
429
- <a href="https://www.val.town/">
430
- <picture width="100%" height="40px">
431
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/36961d2e-d92e-42af-9031-a41885ece5f4">
432
- <img alt="val town logo" src="https://github.com/user-attachments/assets/95305fc4-4da6-4bf8-aea4-bae8f5893e5d" height="40px">
433
- </picture>
434
- </a>
435
- </td>
436
- <td align="center">
437
- <a href="https://www.route4me.com/">
438
- <img src="https://avatars.githubusercontent.com/u/7936820?s=200&v=4" height="40px;" alt="route4me logo" />
439
- </a>
440
- </td>
441
- <td align="center">
442
- <a href="https://encore.dev">
443
- <img src="https://github.com/colinhacks/zod/assets/3084745/5ad94e73-cd34-4957-9979-37da85fcf9cd" height="40px;" alt="Encore.dev logo" />
444
- </a>
445
- </td>
446
- <td align="center">
447
- <a href="https://www.replay.io/">
448
- <img src="https://avatars.githubusercontent.com/u/60818315?s=200&v=4" height="40px;" alt="Replay.io logo" />
449
- </a>
450
- </td>
451
- </tr>
452
- <tr>
453
- <td align="center">
454
- <a href="https://www.numeric.io">
455
- <img src="https://i.imgur.com/kTiLtZt.png" height="40px;" alt="Numeric logo" />
456
- </a>
457
- </td>
458
- <td align="center">
459
- <a href="https://marcatopartners.com">
460
- <img src="https://avatars.githubusercontent.com/u/84106192?s=200&v=4" height="40px;" alt="Marcato Partners" />
461
- </a>
462
- </td>
463
- <td align="center">
464
- <a href="https://interval.com">
465
- <img src="https://avatars.githubusercontent.com/u/67802063?s=200&v=4" height="40px;" alt="" />
466
- </a>
467
- </td>
468
- <td align="center">
469
- <a href="https://seasoned.cc">
470
- <img src="https://avatars.githubusercontent.com/u/33913103?s=200&v=4" height="40px;" alt="" />
471
- </a>
472
- </td>
473
- </tr>
474
- <tr>
475
- <td align="center">
476
- <a href="https://www.bamboocreative.nz/">
477
- <img src="https://avatars.githubusercontent.com/u/41406870?v=4" height="40px;" alt="Bamboo Creative logo" />
478
- </a>
479
- </td>
480
- <td align="center">
481
- <a href="https://github.com/jasonLaster">
482
- <img src="https://avatars.githubusercontent.com/u/254562?v=4" height="40px;" alt="Jason Laster" />
483
- </a>
484
- </td>
485
- </tr>
486
- </table>
487
-
488
- <!-- <h3 align="center">Bronze</h3>
489
-
490
- <table align="center" style="justify-content: center;align-items: center;display: flex;">
491
- <tr>
492
- <td>Brandon Bayer</td>
493
- <td>Jiล™รญ Brabec</td>
494
- <td>Alex Johansson</td>
495
- <td>Fungible Systems</td>
496
- </tr>
497
- <tr>
498
- <td>Adaptable</td>
499
- <td>Avana Wallet</td>
500
- <td>Jason Lengstorf</td>
501
- <td>Global Illumination, Inc.</td>
502
- </tr>
503
- <tr>
504
- <td>MasterBorn</td>
505
- <td>Ryan Palmer</td>
506
- <td>Michael Sweeney</td>
507
- <td>Nextbase</td>
508
- </tr>
509
- <tr>
510
- <td>Remotion</td>
511
- <td>Connor Sinnott</td>
512
- <td>Mohammad-Ali A'rรขbi</td>
513
- <td>Supatool</td>
514
- </tr>
515
- </table> -->
516
-
517
- ### Ecosystem
518
-
519
- There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it [on Twitter](https://twitter.com/colinhacks) or [start a Discussion](https://github.com/colinhacks/zod/discussions). I'll add it below and tweet it out.
520
-
521
- #### Resources
522
-
523
- - [Total TypeScript Zod Tutorial](https://www.totaltypescript.com/tutorials/zod) by [@mattpocockuk](https://twitter.com/mattpocockuk)
524
- - [Fixing TypeScript's Blindspot: Runtime Typechecking](https://www.youtube.com/watch?v=rY_XqfSHock) by [@jherr](https://twitter.com/jherr)
525
-
526
- #### API libraries
527
-
528
- - [`tRPC`](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL.
529
- - [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-nestjs): Helper methods for using Zod in a NestJS project.
530
- - [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible.
531
- - [`zhttp`](https://github.com/evertdespiegeleer/zhttp): An OpenAPI compatible, strictly typed http library with Zod input and response validation.
532
- - [`domain-functions`](https://github.com/SeasonedSoftware/domain-functions/): Decouple your business logic from your framework using composable functions. With first-class type inference from end to end powered by Zod schemas.
533
- - [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod.
534
- - [`express-zod-api`](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares.
535
- - [`tapiduck`](https://github.com/sumukhbarve/monoduck/blob/main/src/tapiduck/README.md): End-to-end typesafe JSON APIs with Zod and Express; a bit like tRPC, but simpler.
536
- - [`koa-zod-router`](https://github.com/JakeFenley/koa-zod-router): Create typesafe routes in Koa with I/O validation using Zod.
537
- - [`zod-sockets`](https://github.com/RobinTail/zod-sockets): Zod-powered Socket.IO microframework with I/O validation and built-in AsyncAPI specs
538
- - [`oas-tszod-gen`](https://github.com/inkognitro/oas-tszod-gen): Client SDK code generator to convert OpenApi v3 specifications into TS endpoint caller functions with Zod types.
539
-
540
- #### Form integrations
541
-
542
- - [`react-hook-form`](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form.
543
- - [`zod-validation-error`](https://github.com/causaly/zod-validation-error): Generate user-friendly error messages from `ZodError`s.
544
- - [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod.
545
- - [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `<form>` generation and validation for React using Zod.
546
- - [`zodix`](https://github.com/rileytomasek/zodix): Zod utilities for FormData and URLSearchParams in Remix loaders and actions.
547
- - [`conform`](https://conform.guide/api/zod/parseWithZod): A typesafe form validation library for progressive enhancement of HTML forms. Works with Remix and Next.js.
548
- - [`remix-params-helper`](https://github.com/kiliman/remix-params-helper): Simplify integration of Zod with standard URLSearchParams and FormData for Remix apps.
549
- - [`formik-validator-zod`](https://github.com/glazy/formik-validator-zod): Formik-compliant validator library that simplifies using Zod with Formik.
550
- - [`zod-i18n-map`](https://github.com/aiji42/zod-i18n): Useful for translating Zod error messages.
551
- - [`@modular-forms/solid`](https://github.com/fabian-hiller/modular-forms): Modular form library for SolidJS that supports Zod for validation.
552
- - [`houseform`](https://github.com/crutchcorn/houseform/): A React form library that uses Zod for validation.
553
- - [`sveltekit-superforms`](https://github.com/ciscoheat/sveltekit-superforms): Supercharged form library for SvelteKit with Zod validation.
554
- - [`mobx-zod-form`](https://github.com/MonoidDev/mobx-zod-form): Data-first form builder based on MobX & Zod.
555
- - [`@vee-validate/zod`](https://github.com/logaretm/vee-validate/tree/main/packages/zod): Form library for Vue.js with Zod schema validation.
556
- - [`zod-form-renderer`](https://github.com/thepeaklab/zod-form-renderer): Auto-infer form fields from zod schema and render them with react-hook-form with E2E type safety.
557
- - [`antd-zod`](https://github.com/MrBr/antd-zod): Zod adapter for Ant Design form fields validation.
558
- - [`frrm`](https://github.com/schalkventer/frrm): Tiny 0.5kb Zod-based, HTML form abstraction that goes brr.
559
-
560
- #### Zod to X
561
-
562
- - [`zod-to-ts`](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas.
563
- - [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema): Convert your Zod schemas into [JSON Schemas](https://json-schema.org/).
564
- - [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`.
565
- - [`zod-fast-check`](https://github.com/DavidTimms/zod-fast-check): Generate `fast-check` arbitraries from Zod schemas.
566
- - [`zod-dto`](https://github.com/kbkk/abitia/tree/master/packages/zod-dto): Generate Nest.js DTOs from a Zod schema.
567
- - [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod): Create Fastify type providers from Zod schemas.
568
- - [`zod-to-openapi`](https://github.com/asteasolutions/zod-to-openapi): Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters.
569
- - [`nestjs-graphql-zod`](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas. Provides GraphQL method decorators working with Zod schemas.
570
- - [`zod-openapi`](https://github.com/samchungy/zod-openapi): Create full OpenAPI v3.x documentation from Zod schemas.
571
- - [`fastify-zod-openapi`](https://github.com/samchungy/fastify-zod-openapi): Fastify type provider, validation, serialization and @fastify/swagger support for Zod schemas.
572
- - [`typeschema`](https://typeschema.com/): Universal adapter for schema validation.
573
- - [`zodex`](https://github.com/commonbaseapp/zodex): (De)serialization for zod schemas
574
-
575
- #### X to Zod
576
-
577
- - [`ts-to-zod`](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas.
578
- - [`@runtyping/zod`](https://github.com/johngeorgewright/runtyping): Generate Zod from static types & JSON schema.
579
- - [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod): Convert your [JSON Schemas](https://json-schema.org/) into Zod schemas. [Live demo](https://StefanTerdell.github.io/json-schema-to-zod-react/).
580
- - [`json-to-zod`](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas. [Live demo](https://rsinohara.github.io/json-to-zod-react/).
581
- - [`graphql-codegen-typescript-validation-schema`](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema): GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema.
582
- - [`zod-prisma`](https://github.com/CarterGrimmeisen/zod-prisma): Generate Zod schemas from your Prisma schema.
583
- - [`Supervillain`](https://github.com/Southclaws/supervillain): Generate Zod schemas from your Go structs.
584
- - [`prisma-zod-generator`](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema.
585
- - [`drizzle-zod`](https://orm.drizzle.team/docs/zod): Emit Zod schemas from your Drizzle schema.
586
- - [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod.
587
- - [`zod-prisma-types`](https://github.com/chrishoermann/zod-prisma-types) Create Zod types from your Prisma models.
588
- - [`quicktype`](https://app.quicktype.io/): Convert JSON objects and JSON schemas into Zod schemas.
589
- - [`@sanity-typed/zod`](https://github.com/saiichihashimoto/sanity-typed/tree/main/packages/zod): Generate Zod Schemas from [Sanity Schemas](https://www.sanity.io/docs/schema-types).
590
- - [`java-to-zod`](https://github.com/ivangreene/java-to-zod): Convert POJOs to Zod schemas
591
- - [`Orval`](https://github.com/anymaniax/orval): Generate Zod schemas from OpenAPI schemas
592
- - [`Kubb`](https://github.com/kubb-labs/kubb): Generate SDKs and Zod schemas from your OpenAPI schemas
593
-
594
- #### Mocking
595
-
596
- - [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/faker-js/faker).
597
- - [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas.
598
- - [`zod-fixture`](https://github.com/timdeschryver/zod-fixture): Use your zod schemas to automate the generation of non-relevant test fixtures in a deterministic way.
599
- - [`zocker`](https://zocker.sigrist.dev): Generate plausible mock-data from your schemas.
600
- - [`zodock`](https://github.com/ItMaga/zodock) Generate mock data based on Zod schemas.
601
- - [`zod-schema-faker`](https://github.com/soc221b/zod-schema-faker) Generates mock data from Zod schemas. Powered by [@faker-js/faker](https://github.com/faker-js/faker) and [randexp.js](https://github.com/fent/randexp.js)
602
-
603
- #### Powered by Zod
604
-
605
- - [`freerstore`](https://github.com/JacobWeisenburger/freerstore): Firestore cost optimizer.
606
- - [`slonik`](https://github.com/gajus/slonik/tree/gajus/add-zod-validation-backwards-compatible#runtime-validation-and-static-type-inference): Node.js Postgres client with strong Zod integration.
607
- - [`schemql`](https://github.com/a2lix/schemql): Enhances your SQL workflow by combining raw SQL with targeted type safety and schema validation.
608
- - [`soly`](https://github.com/mdbetancourt/soly): Create CLI applications with zod.
609
- - [`pastel`](https://github.com/vadimdemedes/pastel): Create CLI applications with react, zod, and ink.
610
- - [`zod-xlsx`](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas.
611
- - [`znv`](https://github.com/lostfictions/znv): Type-safe environment parsing and validation for Node.js with Zod schemas.
612
- - [`zod-config`](https://github.com/alexmarqs/zod-config): Load configurations across multiple sources with flexible adapters, ensuring type safety with Zod.
613
- - [`unplugin-environment`](https://github.com/r17x/js/tree/main/packages/unplugin-environment#readme): A plugin for loading enviroment variables safely with schema validation, simple with virtual module, type-safe with intellisense, and better DX ๐Ÿ”ฅ ๐Ÿš€ ๐Ÿ‘ท. Powered by Zod.
614
- - [`zod-struct`](https://codeberg.org/reesericci/zod-struct): Create runtime-checked structs with Zod.
615
-
616
- #### Utilities for Zod
617
-
618
- - [`zod_utilz`](https://github.com/JacobWeisenburger/zod_utilz): Framework agnostic utilities for Zod.
619
- - [`zod-playground`](https://github.com/marilari88/zod-playground): A tool for learning and testing Zod schema validation functionalities. [Link](https://zod-playground.vercel.app/).
620
- - [`zod-sandbox`](https://github.com/nereumelo/zod-sandbox): Controlled environment for testing zod schemas. [Live demo](https://zod-sandbox.vercel.app/).
621
- - [`zod-dev`](https://github.com/schalkventer/zod-dev): Conditionally disables Zod runtime parsing in production.
622
- - [`zod-accelerator`](https://github.com/duplojs/duplojs-zod-accelerator): Accelerates Zod's throughput up to ~100x.
623
-
624
- ## Installation
625
-
626
- ### Requirements
627
-
628
- - TypeScript 4.5+!
629
- - You must enable `strict` mode in your `tsconfig.json`. This is a best practice for all TypeScript projects.
630
-
631
- ```ts
632
- // tsconfig.json
633
- {
634
- // ...
635
- "compilerOptions": {
636
- // ...
637
- "strict": true
638
- }
639
- }
640
- ```
641
-
642
- ### From `npm`
643
-
644
- ```sh
645
- npm install zod # npm
646
- deno add npm:zod # deno
647
- yarn add zod # yarn
648
- bun add zod # bun
649
- pnpm add zod # pnpm
650
- ```
651
-
652
- Zod also publishes a canary version on every commit. To install the canary:
653
-
654
- ```sh
655
- npm install zod@canary # npm
656
- deno add npm:zod@canary # deno
657
- yarn add zod@canary # yarn
658
- bun add zod@canary # bun
659
- pnpm add zod@canary # pnpm
660
- ```
661
-
662
- > The rest of this README assumes you are using npm and importing directly from the `"zod"` package.
663
-
664
- ## Basic usage
665
-
666
- Creating a simple string schema
667
-
668
- ```ts
669
- import { z } from "zod";
670
-
671
- // creating a schema for strings
672
- const mySchema = z.string();
673
-
674
- // parsing
675
- mySchema.parse("tuna"); // => "tuna"
676
- mySchema.parse(12); // => throws ZodError
677
-
678
- // "safe" parsing (doesn't throw error if validation fails)
679
- mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
680
- mySchema.safeParse(12); // => { success: false; error: ZodError }
681
- ```
682
-
683
- Creating an object schema
684
-
685
- ```ts
686
- import { z } from "zod";
687
-
688
- const User = z.object({
689
- username: z.string(),
690
- });
691
-
692
- User.parse({ username: "Ludwig" });
693
-
694
- // extract the inferred type
695
- type User = z.infer<typeof User>;
696
- // { username: string }
697
- ```
698
-
699
- ## Primitives
700
-
701
- ```ts
702
- import { z } from "zod";
703
-
704
- // primitive values
705
- z.string();
706
- z.number();
707
- z.bigint();
708
- z.boolean();
709
- z.date();
710
- z.symbol();
711
-
712
- // empty types
713
- z.undefined();
714
- z.null();
715
- z.void(); // accepts undefined
716
-
717
- // catch-all types
718
- // allows any value
719
- z.any();
720
- z.unknown();
721
-
722
- // never type
723
- // allows no values
724
- z.never();
725
- ```
726
-
727
- ## Coercion for primitives
728
-
729
- Zod now provides a more convenient way to coerce primitive values.
730
-
731
- ```ts
732
- const schema = z.coerce.string();
733
- schema.parse("tuna"); // => "tuna"
734
- schema.parse(12); // => "12"
735
- ```
736
-
737
- During the parsing step, the input is passed through the `String()` function, which is a JavaScript built-in for coercing data into strings.
738
-
739
- ```ts
740
- schema.parse(12); // => "12"
741
- schema.parse(true); // => "true"
742
- schema.parse(undefined); // => "undefined"
743
- schema.parse(null); // => "null"
744
- ```
745
-
746
- The returned schema is a normal `ZodString` instance so you can use all string methods.
747
-
748
- ```ts
749
- z.coerce.string().email().min(5);
750
- ```
751
-
752
- **How coercion works**
753
-
754
- All primitive types support coercion. Zod coerces all inputs using the built-in constructors: `String(input)`, `Number(input)`, `new Date(input)`, etc.
755
-
756
- ```ts
757
- z.coerce.string(); // String(input)
758
- z.coerce.number(); // Number(input)
759
- z.coerce.boolean(); // Boolean(input)
760
- z.coerce.bigint(); // BigInt(input)
761
- z.coerce.date(); // new Date(input)
762
- ```
763
-
764
- **Note** โ€”ย Boolean coercion with `z.coerce.boolean()` may not work how you expect. Any [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value is coerced to `true`, and any [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value is coerced to `false`.
765
-
766
- ```ts
767
- const schema = z.coerce.boolean(); // Boolean(input)
768
-
769
- schema.parse("tuna"); // => true
770
- schema.parse("true"); // => true
771
- schema.parse("false"); // => true
772
- schema.parse(1); // => true
773
- schema.parse([]); // => true
774
-
775
- schema.parse(0); // => false
776
- schema.parse(""); // => false
777
- schema.parse(undefined); // => false
778
- schema.parse(null); // => false
779
- ```
780
-
781
- For more control over coercion logic, consider using [`z.preprocess`](#preprocess) or [`z.pipe()`](#pipe).
782
-
783
- ## Literals
784
-
785
- Literal schemas represent a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types), like `"hello world"` or `5`.
786
-
787
- ```ts
788
- const tuna = z.literal("tuna");
789
- const twelve = z.literal(12);
790
- const twobig = z.literal(2n); // bigint literal
791
- const tru = z.literal(true);
792
-
793
- const terrificSymbol = Symbol("terrific");
794
- const terrific = z.literal(terrificSymbol);
795
-
796
- // retrieve literal value
797
- tuna.value; // "tuna"
798
- ```
799
-
800
- > Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue.
801
-
802
- ## Strings
803
-
804
- Zod includes a handful of string-specific validations.
805
-
806
- ```ts
807
- // validations
808
- z.string().max(5);
809
- z.string().min(5);
810
- z.string().length(5);
811
- z.string().email();
812
- z.string().url();
813
- z.string().emoji();
814
- z.string().uuid();
815
- z.string().nanoid();
816
- z.string().cuid();
817
- z.string().cuid2();
818
- z.string().ulid();
819
- z.string().regex(regex);
820
- z.string().includes(string);
821
- z.string().startsWith(string);
822
- z.string().endsWith(string);
823
- z.string().datetime(); // ISO 8601; by default only `Z` timezone allowed
824
- z.string().ip(); // defaults to allow both IPv4 and IPv6
825
- z.string().cidr(); // defaults to allow both IPv4 and IPv6
826
-
827
- // transforms
828
- z.string().trim(); // trim whitespace
829
- z.string().toLowerCase(); // toLowerCase
830
- z.string().toUpperCase(); // toUpperCase
831
-
832
- // added in Zod 3.23
833
- z.string().date(); // ISO date format (YYYY-MM-DD)
834
- z.string().time(); // ISO time format (HH:mm:ss[.SSSSSS])
835
- z.string().duration(); // ISO 8601 duration
836
- z.string().base64();
837
- ```
838
-
839
- > Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions that can be used in conjunction with [Refinements](#refine).
840
-
841
- You can customize some common error messages when creating a string schema.
842
-
843
- ```ts
844
- const name = z.string({
845
- required_error: "Name is required",
846
- invalid_type_error: "Name must be a string",
847
- });
848
- ```
849
-
850
- When using validation methods, you can pass in an additional argument to provide a custom error message.
851
-
852
- ```ts
853
- z.string().min(5, { message: "Must be 5 or more characters long" });
854
- z.string().max(5, { message: "Must be 5 or fewer characters long" });
855
- z.string().length(5, { message: "Must be exactly 5 characters long" });
856
- z.string().email({ message: "Invalid email address" });
857
- z.string().url({ message: "Invalid url" });
858
- z.string().emoji({ message: "Contains non-emoji characters" });
859
- z.string().uuid({ message: "Invalid UUID" });
860
- z.string().includes("tuna", { message: "Must include tuna" });
861
- z.string().startsWith("https://", { message: "Must provide secure URL" });
862
- z.string().endsWith(".com", { message: "Only .com domains allowed" });
863
- z.string().datetime({ message: "Invalid datetime string! Must be UTC." });
864
- z.string().date({ message: "Invalid date string!" });
865
- z.string().time({ message: "Invalid time string!" });
866
- z.string().ip({ message: "Invalid IP address" });
867
- z.string().cidr({ message: "Invalid CIDR" });
868
- ```
869
-
870
- ### Datetimes
871
-
872
- As you may have noticed, Zod string includes a few date/time related validations. These validations are regular expression based, so they are not as strict as a full date/time library. However, they are very convenient for validating user input.
873
-
874
- The `z.string().datetime()` method enforces ISO 8601; default is no timezone offsets and arbitrary sub-second decimal precision.
875
-
876
- ```ts
877
- const datetime = z.string().datetime();
878
-
879
- datetime.parse("2020-01-01T00:00:00Z"); // pass
880
- datetime.parse("2020-01-01T00:00:00.123Z"); // pass
881
- datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision)
882
- datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed)
883
- ```
884
-
885
- Timezone offsets can be allowed by setting the `offset` option to `true`.
886
-
887
- ```ts
888
- const datetime = z.string().datetime({ offset: true });
889
-
890
- datetime.parse("2020-01-01T00:00:00+02:00"); // pass
891
- datetime.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional)
892
- datetime.parse("2020-01-01T00:00:00.123+0200"); // pass (millis optional)
893
- datetime.parse("2020-01-01T00:00:00.123+02"); // pass (only offset hours)
894
- datetime.parse("2020-01-01T00:00:00Z"); // pass (Z still supported)
895
- ```
896
-
897
- Allow unqualified (timezone-less) datetimes with the `local` flag.
898
-
899
- ```ts
900
- const schema = z.string().datetime({ local: true });
901
- schema.parse("2020-01-01T00:00:00"); // pass
902
- ```
903
-
904
- You can additionally constrain the allowable `precision`. By default, arbitrary sub-second precision is supported (but optional).
905
-
906
- ```ts
907
- const datetime = z.string().datetime({ precision: 3 });
908
-
909
- datetime.parse("2020-01-01T00:00:00.123Z"); // pass
910
- datetime.parse("2020-01-01T00:00:00Z"); // fail
911
- datetime.parse("2020-01-01T00:00:00.123456Z"); // fail
912
- ```
913
-
914
- ### Dates
915
-
916
- > Added in Zod 3.23
917
-
918
- The `z.string().date()` method validates strings in the format `YYYY-MM-DD`.
919
-
920
- ```ts
921
- const date = z.string().date();
922
-
923
- date.parse("2020-01-01"); // pass
924
- date.parse("2020-1-1"); // fail
925
- date.parse("2020-01-32"); // fail
926
- ```
927
-
928
- ### Times
929
-
930
- > Added in Zod 3.23
931
-
932
- The `z.string().time()` method validates strings in the format `HH:MM:SS[.s+]`. The second can include arbitrary decimal precision. It does not allow timezone offsets of any kind.
933
-
934
- ```ts
935
- const time = z.string().time();
936
-
937
- time.parse("00:00:00"); // pass
938
- time.parse("09:52:31"); // pass
939
- time.parse("23:59:59.9999999"); // pass (arbitrary precision)
940
-
941
- time.parse("00:00:00.123Z"); // fail (no `Z` allowed)
942
- time.parse("00:00:00.123+02:00"); // fail (no offsets allowed)
943
- ```
944
-
945
- You can set the `precision` option to constrain the allowable decimal precision.
946
-
947
- ```ts
948
- const time = z.string().time({ precision: 3 });
949
-
950
- time.parse("00:00:00.123"); // pass
951
- time.parse("00:00:00.123456"); // fail
952
- time.parse("00:00:00"); // fail
953
- ```
954
-
955
- ### IP addresses
956
-
957
- By default `.ip()` allows both IPv4 and IPv6.
958
-
959
- ```ts
960
- const ip = z.string().ip();
961
-
962
- ip.parse("192.168.1.1"); // pass
963
- ip.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003"); // pass
964
- ip.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:192.168.1.1"); // pass
965
-
966
- ip.parse("256.1.1.1"); // fail
967
- ip.parse("84d5:51a0:9114:gggg:4cfa:f2d7:1f12:7003"); // fail
968
- ```
969
-
970
- You can additionally set the IP `version`.
971
-
972
- ```ts
973
- const ipv4 = z.string().ip({ version: "v4" });
974
- ipv4.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003"); // fail
975
-
976
- const ipv6 = z.string().ip({ version: "v6" });
977
- ipv6.parse("192.168.1.1"); // fail
978
- ```
979
-
980
- ### IP ranges (CIDR)
981
-
982
- Validate IP address ranges specified with [CIDR notation](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing). By default, `.cidr()` allows both IPv4 and IPv6.
983
-
984
- ```ts
985
- const cidr = z.string().cidr();
986
- cidr.parse("192.168.0.0/24"); // pass
987
- cidr.parse("2001:db8::/32"); // pass
988
- ```
989
-
990
- You can specify a version with the `version` parameter.
991
-
992
- ```ts
993
- const ipv4Cidr = z.string().cidr({ version: "v4" });
994
- ipv4Cidr.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003"); // fail
995
-
996
- const ipv6Cidr = z.string().cidr({ version: "v6" });
997
- ipv6Cidr.parse("192.168.1.1"); // fail
998
- ```
999
-
1000
- ## Numbers
1001
-
1002
- You can customize certain error messages when creating a number schema.
1003
-
1004
- ```ts
1005
- const age = z.number({
1006
- required_error: "Age is required",
1007
- invalid_type_error: "Age must be a number",
1008
- });
1009
- ```
1010
-
1011
- Zod includes a handful of number-specific validations.
1012
-
1013
- ```ts
1014
- z.number().gt(5);
1015
- z.number().gte(5); // alias .min(5)
1016
- z.number().lt(5);
1017
- z.number().lte(5); // alias .max(5)
1018
-
1019
- z.number().int(); // value must be an integer
1020
-
1021
- z.number().positive(); // > 0
1022
- z.number().nonnegative(); // >= 0
1023
- z.number().negative(); // < 0
1024
- z.number().nonpositive(); // <= 0
1025
-
1026
- z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5)
1027
-
1028
- z.number().finite(); // value must be finite, not Infinity or -Infinity
1029
- z.number().safe(); // value must be between Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER
1030
- ```
1031
-
1032
- Optionally, you can pass in a second argument to provide a custom error message.
1033
-
1034
- ```ts
1035
- z.number().lte(5, { message: "this๐Ÿ‘is๐Ÿ‘too๐Ÿ‘big" });
1036
- ```
1037
-
1038
- ## BigInts
1039
-
1040
- Zod includes a handful of bigint-specific validations.
1041
-
1042
- ```ts
1043
- z.bigint().gt(5n);
1044
- z.bigint().gte(5n); // alias `.min(5n)`
1045
- z.bigint().lt(5n);
1046
- z.bigint().lte(5n); // alias `.max(5n)`
1047
-
1048
- z.bigint().positive(); // > 0n
1049
- z.bigint().nonnegative(); // >= 0n
1050
- z.bigint().negative(); // < 0n
1051
- z.bigint().nonpositive(); // <= 0n
1052
-
1053
- z.bigint().multipleOf(5n); // Evenly divisible by 5n.
1054
- ```
1055
-
1056
- ## NaNs
1057
-
1058
- You can customize certain error messages when creating a nan schema.
1059
-
1060
- ```ts
1061
- const isNaN = z.nan({
1062
- required_error: "isNaN is required",
1063
- invalid_type_error: "isNaN must be 'not a number'",
1064
- });
1065
- ```
1066
-
1067
- ## Booleans
1068
-
1069
- You can customize certain error messages when creating a boolean schema.
1070
-
1071
- ```ts
1072
- const isActive = z.boolean({
1073
- required_error: "isActive is required",
1074
- invalid_type_error: "isActive must be a boolean",
1075
- });
1076
- ```
1077
-
1078
- ## Dates
1079
-
1080
- Use z.date() to validate `Date` instances.
1081
-
1082
- ```ts
1083
- z.date().safeParse(new Date()); // success: true
1084
- z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false
1085
- ```
1086
-
1087
- You can customize certain error messages when creating a date schema.
1088
-
1089
- ```ts
1090
- const myDateSchema = z.date({
1091
- required_error: "Please select a date and time",
1092
- invalid_type_error: "That's not a date!",
1093
- });
1094
- ```
1095
-
1096
- Zod provides a handful of date-specific validations.
1097
-
1098
- ```ts
1099
- z.date().min(new Date("1900-01-01"), { message: "Too old" });
1100
- z.date().max(new Date(), { message: "Too young!" });
1101
- ```
1102
-
1103
- **Coercion to Date**
1104
-
1105
- Since [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`.
1106
-
1107
- ```ts
1108
- const dateSchema = z.coerce.date();
1109
- type DateSchema = z.infer<typeof dateSchema>;
1110
- // type DateSchema = Date
1111
-
1112
- /* valid dates */
1113
- console.log(dateSchema.safeParse("2023-01-10T00:00:00.000Z").success); // true
1114
- console.log(dateSchema.safeParse("2023-01-10").success); // true
1115
- console.log(dateSchema.safeParse("1/10/23").success); // true
1116
- console.log(dateSchema.safeParse(new Date("1/10/23")).success); // true
1117
-
1118
- /* invalid dates */
1119
- console.log(dateSchema.safeParse("2023-13-10").success); // false
1120
- console.log(dateSchema.safeParse("0000-00-00").success); // false
1121
- ```
1122
-
1123
- For older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276).
1124
-
1125
- ## Zod enums
1126
-
1127
- ```ts
1128
- const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
1129
- type FishEnum = z.infer<typeof FishEnum>;
1130
- // 'Salmon' | 'Tuna' | 'Trout'
1131
- ```
1132
-
1133
- `z.enum` is a Zod-native way to declare a schema with a fixed set of allowable _string_ values. Pass the array of values directly into `z.enum()`. Alternatively, use `as const` to define your enum values as a tuple of strings. See the [const assertion docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) for details.
1134
-
1135
- ```ts
1136
- const VALUES = ["Salmon", "Tuna", "Trout"] as const;
1137
- const FishEnum = z.enum(VALUES);
1138
- ```
1139
-
1140
- This is not allowed, since Zod isn't able to infer the exact values of each element.
1141
-
1142
- ```ts
1143
- const fish = ["Salmon", "Tuna", "Trout"];
1144
- const FishEnum = z.enum(fish);
1145
- ```
1146
-
1147
- **`.enum`**
1148
-
1149
- To get autocompletion with a Zod enum, use the `.enum` property of your schema:
1150
-
1151
- ```ts
1152
- FishEnum.enum.Salmon; // => autocompletes
1153
-
1154
- FishEnum.enum;
1155
- /*
1156
- => {
1157
- Salmon: "Salmon",
1158
- Tuna: "Tuna",
1159
- Trout: "Trout",
1160
- }
1161
- */
1162
- ```
1163
-
1164
- You can also retrieve the list of options as a tuple with the `.options` property:
1165
-
1166
- ```ts
1167
- FishEnum.options; // ["Salmon", "Tuna", "Trout"];
1168
- ```
1169
-
1170
- **`.exclude/.extract()`**
1171
-
1172
- You can create subsets of a Zod enum with the `.exclude` and `.extract` methods.
1173
-
1174
- ```ts
1175
- const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
1176
- const SalmonAndTrout = FishEnum.extract(["Salmon", "Trout"]);
1177
- const TunaOnly = FishEnum.exclude(["Salmon", "Trout"]);
1178
- ```
1179
-
1180
- ## Native enums
1181
-
1182
- Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use `z.nativeEnum()`.
1183
-
1184
- **Numeric enums**
1185
-
1186
- ```ts
1187
- enum Fruits {
1188
- Apple,
1189
- Banana,
1190
- }
1191
-
1192
- const FruitEnum = z.nativeEnum(Fruits);
1193
- type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
1194
-
1195
- FruitEnum.parse(Fruits.Apple); // passes
1196
- FruitEnum.parse(Fruits.Banana); // passes
1197
- FruitEnum.parse(0); // passes
1198
- FruitEnum.parse(1); // passes
1199
- FruitEnum.parse(3); // fails
1200
- ```
1201
-
1202
- **String enums**
1203
-
1204
- ```ts
1205
- enum Fruits {
1206
- Apple = "apple",
1207
- Banana = "banana",
1208
- Cantaloupe, // you can mix numerical and string enums
1209
- }
1210
-
1211
- const FruitEnum = z.nativeEnum(Fruits);
1212
- type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
1213
-
1214
- FruitEnum.parse(Fruits.Apple); // passes
1215
- FruitEnum.parse(Fruits.Cantaloupe); // passes
1216
- FruitEnum.parse("apple"); // passes
1217
- FruitEnum.parse("banana"); // passes
1218
- FruitEnum.parse(0); // passes
1219
- FruitEnum.parse("Cantaloupe"); // fails
1220
- ```
1221
-
1222
- **Const enums**
1223
-
1224
- The `.nativeEnum()` function works for `as const` objects as well. โš ๏ธ `as const` requires TypeScript 3.4+!
1225
-
1226
- ```ts
1227
- const Fruits = {
1228
- Apple: "apple",
1229
- Banana: "banana",
1230
- Cantaloupe: 3,
1231
- } as const;
1232
-
1233
- const FruitEnum = z.nativeEnum(Fruits);
1234
- type FruitEnum = z.infer<typeof FruitEnum>; // "apple" | "banana" | 3
1235
-
1236
- FruitEnum.parse("apple"); // passes
1237
- FruitEnum.parse("banana"); // passes
1238
- FruitEnum.parse(3); // passes
1239
- FruitEnum.parse("Cantaloupe"); // fails
1240
- ```
1241
-
1242
- You can access the underlying object with the `.enum` property:
1243
-
1244
- ```ts
1245
- FruitEnum.enum.Apple; // "apple"
1246
- ```
1247
-
1248
- ## Optionals
1249
-
1250
- You can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result.
1251
-
1252
- ```ts
1253
- const schema = z.optional(z.string());
1254
-
1255
- schema.parse(undefined); // => returns undefined
1256
- type A = z.infer<typeof schema>; // string | undefined
1257
- ```
1258
-
1259
- For convenience, you can also call the `.optional()` method on an existing schema.
1260
-
1261
- ```ts
1262
- const user = z.object({
1263
- username: z.string().optional(),
1264
- });
1265
- type C = z.infer<typeof user>; // { username?: string | undefined };
1266
- ```
1267
-
1268
- You can extract the wrapped schema from a `ZodOptional` instance with `.unwrap()`.
1269
-
1270
- ```ts
1271
- const stringSchema = z.string();
1272
- const optionalString = stringSchema.optional();
1273
- optionalString.unwrap() === stringSchema; // true
1274
- ```
1275
-
1276
- ## Nullables
1277
-
1278
- Similarly, you can create nullable types with `z.nullable()`.
1279
-
1280
- ```ts
1281
- const nullableString = z.nullable(z.string());
1282
- nullableString.parse("asdf"); // => "asdf"
1283
- nullableString.parse(null); // => null
1284
- ```
1285
-
1286
- Or use the `.nullable()` method.
1287
-
1288
- ```ts
1289
- const E = z.string().nullable(); // equivalent to nullableString
1290
- type E = z.infer<typeof E>; // string | null
1291
- ```
1292
-
1293
- Extract the inner schema with `.unwrap()`.
1294
-
1295
- ```ts
1296
- const stringSchema = z.string();
1297
- const nullableString = stringSchema.nullable();
1298
- nullableString.unwrap() === stringSchema; // true
1299
- ```
1300
-
1301
- ## Objects
1302
-
1303
- ```ts
1304
- // all properties are required by default
1305
- const Dog = z.object({
1306
- name: z.string(),
1307
- age: z.number(),
1308
- });
1309
-
1310
- // extract the inferred type like this
1311
- type Dog = z.infer<typeof Dog>;
1312
-
1313
- // equivalent to:
1314
- type Dog = {
1315
- name: string;
1316
- age: number;
1317
- };
1318
- ```
1319
-
1320
- ### `.shape`
1321
-
1322
- Use `.shape` to access the schemas for a particular key.
1323
-
1324
- ```ts
1325
- Dog.shape.name; // => string schema
1326
- Dog.shape.age; // => number schema
1327
- ```
1328
-
1329
- ### `.keyof`
1330
-
1331
- Use `.keyof` to create a `ZodEnum` schema from the keys of an object schema.
1332
-
1333
- ```ts
1334
- const keySchema = Dog.keyof();
1335
- keySchema; // ZodEnum<["name", "age"]>
1336
- ```
1337
-
1338
- ### `.extend`
1339
-
1340
- You can add additional fields to an object schema with the `.extend` method.
1341
-
1342
- ```ts
1343
- const DogWithBreed = Dog.extend({
1344
- breed: z.string(),
1345
- });
1346
- ```
1347
-
1348
- You can use `.extend` to overwrite fields! Be careful with this power!
1349
-
1350
- ### `.merge`
1351
-
1352
- Equivalent to `A.extend(B.shape)`.
1353
-
1354
- ```ts
1355
- const BaseTeacher = z.object({ students: z.array(z.string()) });
1356
- const HasID = z.object({ id: z.string() });
1357
-
1358
- const Teacher = BaseTeacher.merge(HasID);
1359
- type Teacher = z.infer<typeof Teacher>; // => { students: string[], id: string }
1360
- ```
1361
-
1362
- > If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B.
1363
-
1364
- ### `.pick/.omit`
1365
-
1366
- Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a modified version. Consider this Recipe schema:
1367
-
1368
- ```ts
1369
- const Recipe = z.object({
1370
- id: z.string(),
1371
- name: z.string(),
1372
- ingredients: z.array(z.string()),
1373
- });
1374
- ```
1375
-
1376
- To only keep certain keys, use `.pick` .
1377
-
1378
- ```ts
1379
- const JustTheName = Recipe.pick({ name: true });
1380
- type JustTheName = z.infer<typeof JustTheName>;
1381
- // => { name: string }
1382
- ```
1383
-
1384
- To remove certain keys, use `.omit` .
1385
-
1386
- ```ts
1387
- const NoIDRecipe = Recipe.omit({ id: true });
1388
-
1389
- type NoIDRecipe = z.infer<typeof NoIDRecipe>;
1390
- // => { name: string, ingredients: string[] }
1391
- ```
1392
-
1393
- ### `.partial`
1394
-
1395
- Inspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype), the `.partial` method makes all properties optional.
1396
-
1397
- Starting from this object:
1398
-
1399
- ```ts
1400
- const user = z.object({
1401
- email: z.string(),
1402
- username: z.string(),
1403
- });
1404
- // { email: string; username: string }
1405
- ```
1406
-
1407
- We can create a partial version:
1408
-
1409
- ```ts
1410
- const partialUser = user.partial();
1411
- // { email?: string | undefined; username?: string | undefined }
1412
- ```
1413
-
1414
- You can also specify which properties to make optional:
1415
-
1416
- ```ts
1417
- const optionalEmail = user.partial({
1418
- email: true,
1419
- });
1420
- /*
1421
- {
1422
- email?: string | undefined;
1423
- username: string
1424
- }
1425
- */
1426
- ```
1427
-
1428
- ### `.deepPartial`
1429
-
1430
- The `.partial` method is shallow โ€” it only applies one level deep. There is also a "deep" version:
1431
-
1432
- ```ts
1433
- const user = z.object({
1434
- username: z.string(),
1435
- location: z.object({
1436
- latitude: z.number(),
1437
- longitude: z.number(),
1438
- }),
1439
- strings: z.array(z.object({ value: z.string() })),
1440
- });
1441
-
1442
- const deepPartialUser = user.deepPartial();
1443
-
1444
- /*
1445
- {
1446
- username?: string | undefined,
1447
- location?: {
1448
- latitude?: number | undefined;
1449
- longitude?: number | undefined;
1450
- } | undefined,
1451
- strings?: { value?: string}[]
1452
- }
1453
- */
1454
- ```
1455
-
1456
- > Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.
1457
-
1458
- ### `.required`
1459
-
1460
- Contrary to the `.partial` method, the `.required` method makes all properties required.
1461
-
1462
- Starting from this object:
1463
-
1464
- ```ts
1465
- const user = z
1466
- .object({
1467
- email: z.string(),
1468
- username: z.string(),
1469
- })
1470
- .partial();
1471
- // { email?: string | undefined; username?: string | undefined }
1472
- ```
1473
-
1474
- We can create a required version:
1475
-
1476
- ```ts
1477
- const requiredUser = user.required();
1478
- // { email: string; username: string }
1479
- ```
1480
-
1481
- You can also specify which properties to make required:
1482
-
1483
- ```ts
1484
- const requiredEmail = user.required({
1485
- email: true,
1486
- });
1487
- /*
1488
- {
1489
- email: string;
1490
- username?: string | undefined;
1491
- }
1492
- */
1493
- ```
1494
-
1495
- ### `.passthrough`
1496
-
1497
- By default Zod object schemas strip out unrecognized keys during parsing.
1498
-
1499
- ```ts
1500
- const person = z.object({
1501
- name: z.string(),
1502
- });
1503
-
1504
- person.parse({
1505
- name: "bob dylan",
1506
- extraKey: 61,
1507
- });
1508
- // => { name: "bob dylan" }
1509
- // extraKey has been stripped
1510
- ```
1511
-
1512
- Instead, if you want to pass through unknown keys, use `.passthrough()` .
1513
-
1514
- ```ts
1515
- person.passthrough().parse({
1516
- name: "bob dylan",
1517
- extraKey: 61,
1518
- });
1519
- // => { name: "bob dylan", extraKey: 61 }
1520
- ```
1521
-
1522
- ### `.strict`
1523
-
1524
- By default Zod object schemas strip out unrecognized keys during parsing. You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error.
1525
-
1526
- ```ts
1527
- const person = z
1528
- .object({
1529
- name: z.string(),
1530
- })
1531
- .strict();
1532
-
1533
- person.parse({
1534
- name: "bob dylan",
1535
- extraKey: 61,
1536
- });
1537
- // => throws ZodError
1538
- ```
1539
-
1540
- ### `.strip`
1541
-
1542
- You can use the `.strip` method to reset an object schema to the default behavior (stripping unrecognized keys).
1543
-
1544
- ### `.catchall`
1545
-
1546
- You can pass a "catchall" schema into an object schema. All unknown keys will be validated against it.
1547
-
1548
- ```ts
1549
- const person = z
1550
- .object({
1551
- name: z.string(),
1552
- })
1553
- .catchall(z.number());
1554
-
1555
- person.parse({
1556
- name: "bob dylan",
1557
- validExtraKey: 61, // works fine
1558
- });
1559
-
1560
- person.parse({
1561
- name: "bob dylan",
1562
- validExtraKey: false, // fails
1563
- });
1564
- // => throws ZodError
1565
- ```
1566
-
1567
- Using `.catchall()` obviates `.passthrough()` , `.strip()` , or `.strict()`. All keys are now considered "known".
1568
-
1569
- ## Arrays
1570
-
1571
- ```ts
1572
- const stringArray = z.array(z.string());
1573
-
1574
- // equivalent
1575
- const stringArray = z.string().array();
1576
- ```
1577
-
1578
- Be careful with the `.array()` method. It returns a new `ZodArray` instance. This means the _order_ in which you call methods matters. For instance:
1579
-
1580
- ```ts
1581
- z.string().optional().array(); // (string | undefined)[]
1582
- z.string().array().optional(); // string[] | undefined
1583
- ```
1584
-
1585
- ### `.element`
1586
-
1587
- Use `.element` to access the schema for an element of the array.
1588
-
1589
- ```ts
1590
- stringArray.element; // => string schema
1591
- ```
1592
-
1593
- ### `.nonempty`
1594
-
1595
- If you want to ensure that an array contains at least one element, use `.nonempty()`.
1596
-
1597
- ```ts
1598
- const nonEmptyStrings = z.string().array().nonempty();
1599
- // the inferred type is now
1600
- // [string, ...string[]]
1601
-
1602
- nonEmptyStrings.parse([]); // throws: "Array cannot be empty"
1603
- nonEmptyStrings.parse(["Ariana Grande"]); // passes
1604
- ```
1605
-
1606
- You can optionally specify a custom error message:
1607
-
1608
- ```ts
1609
- // optional custom error message
1610
- const nonEmptyStrings = z.string().array().nonempty({
1611
- message: "Can't be empty!",
1612
- });
1613
- ```
1614
-
1615
- ### `.min/.max/.length`
1616
-
1617
- ```ts
1618
- z.string().array().min(5); // must contain 5 or more items
1619
- z.string().array().max(5); // must contain 5 or fewer items
1620
- z.string().array().length(5); // must contain 5 items exactly
1621
- ```
1622
-
1623
- Unlike `.nonempty()` these methods do not change the inferred type.
1624
-
1625
- ## Tuples
1626
-
1627
- Unlike arrays, tuples have a fixed number of elements and each element can have a different type.
1628
-
1629
- ```ts
1630
- const athleteSchema = z.tuple([
1631
- z.string(), // name
1632
- z.number(), // jersey number
1633
- z.object({
1634
- pointsScored: z.number(),
1635
- }), // statistics
1636
- ]);
1637
-
1638
- type Athlete = z.infer<typeof athleteSchema>;
1639
- // type Athlete = [string, number, { pointsScored: number }]
1640
- ```
1641
-
1642
- A variadic ("rest") argument can be added with the `.rest` method.
1643
-
1644
- ```ts
1645
- const variadicTuple = z.tuple([z.string()]).rest(z.number());
1646
- const result = variadicTuple.parse(["hello", 1, 2, 3]);
1647
- // => [string, ...number[]];
1648
- ```
1649
-
1650
- ## Unions
1651
-
1652
- Zod includes a built-in `z.union` method for composing "OR" types.
1653
-
1654
- ```ts
1655
- const stringOrNumber = z.union([z.string(), z.number()]);
1656
-
1657
- stringOrNumber.parse("foo"); // passes
1658
- stringOrNumber.parse(14); // passes
1659
- ```
1660
-
1661
- Zod will test the input against each of the "options" in order and return the first value that validates successfully.
1662
-
1663
- For convenience, you can also use the [`.or` method](#or):
1664
-
1665
- ```ts
1666
- const stringOrNumber = z.string().or(z.number());
1667
- ```
1668
-
1669
- **Optional string validation:**
1670
-
1671
- To validate an optional form input, you can union the desired string validation with an empty string [literal](#literals).
1672
-
1673
- This example validates an input that is optional but needs to contain a [valid URL](#strings):
1674
-
1675
- ```ts
1676
- const optionalUrl = z.union([z.string().url().nullish(), z.literal("")]);
1677
-
1678
- console.log(optionalUrl.safeParse(undefined).success); // true
1679
- console.log(optionalUrl.safeParse(null).success); // true
1680
- console.log(optionalUrl.safeParse("").success); // true
1681
- console.log(optionalUrl.safeParse("https://zod.dev").success); // true
1682
- console.log(optionalUrl.safeParse("not a valid url").success); // false
1683
- ```
1684
-
1685
- ## Discriminated unions
1686
-
1687
- A discriminated union is a union of object schemas that all share a particular key.
1688
-
1689
- ```ts
1690
- type MyUnion =
1691
- | { status: "success"; data: string }
1692
- | { status: "failed"; error: Error };
1693
- ```
1694
-
1695
- Such unions can be represented with the `z.discriminatedUnion` method. This enables faster evaluation, because Zod can check the _discriminator key_ (`status` in the example above) to determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod report friendlier errors.
1696
-
1697
- With the basic union method, the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option".
1698
-
1699
- ```ts
1700
- const myUnion = z.discriminatedUnion("status", [
1701
- z.object({ status: z.literal("success"), data: z.string() }),
1702
- z.object({ status: z.literal("failed"), error: z.instanceof(Error) }),
1703
- ]);
1704
-
1705
- myUnion.parse({ status: "success", data: "yippie ki yay" });
1706
- ```
1707
-
1708
- You can extract a reference to the array of schemas with the `.options` property.
1709
-
1710
- ```ts
1711
- myUnion.options; // [ZodObject<...>, ZodObject<...>]
1712
- ```
1713
-
1714
- To merge two or more discriminated unions, use `.options` with destructuring.
1715
-
1716
- ```ts
1717
- const A = z.discriminatedUnion("status", [
1718
- /* options */
1719
- ]);
1720
- const B = z.discriminatedUnion("status", [
1721
- /* options */
1722
- ]);
1723
-
1724
- const AB = z.discriminatedUnion("status", [...A.options, ...B.options]);
1725
- ```
1726
-
1727
- ## Records
1728
-
1729
- Record schemas are used to validate types such as `Record<string, number>`. This is particularly useful for storing or caching items by ID.
1730
-
1731
- <!-- If you want to validate the _values_ of an object against some schema but don't care about the keys, use `z.record(valueType)`:
1732
-
1733
- ```ts
1734
- const NumberCache = z.record(z.number());
1735
-
1736
- type NumberCache = z.infer<typeof NumberCache>;
1737
- // => { [k: string]: number }
1738
- ``` -->
1739
-
1740
- ```ts
1741
- const User = z.object({ name: z.string() });
1742
-
1743
- const UserStore = z.record(z.string(), User);
1744
- type UserStore = z.infer<typeof UserStore>;
1745
- // => Record<string, { name: string }>
1746
- ```
1747
-
1748
- The schema and inferred type can be used like so:
1749
-
1750
- ```ts
1751
- const userStore: UserStore = {};
1752
-
1753
- userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
1754
- name: "Carlotta",
1755
- }; // passes
1756
-
1757
- userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
1758
- whatever: "Ice cream sundae",
1759
- }; // TypeError
1760
- ```
1761
-
1762
- **A note on numerical keys**
1763
-
1764
- While `z.record(keyType, valueType)` is able to accept numerical key types and TypeScript's built-in Record type is `Record<KeyType, ValueType>`, it's hard to represent the TypeScript type `Record<number, any>` in Zod.
1765
-
1766
- As it turns out, TypeScript's behavior surrounding `[k: number]` is a little unintuitive:
1767
-
1768
- ```ts
1769
- const testMap: { [k: number]: string } = {
1770
- 1: "one",
1771
- };
1772
-
1773
- for (const key in testMap) {
1774
- console.log(`${key}: ${typeof key}`);
1775
- }
1776
- // prints: `1: string`
1777
- ```
1778
-
1779
- As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.
1780
-
1781
- ## Maps
1782
-
1783
- ```ts
1784
- const stringNumberMap = z.map(z.string(), z.number());
1785
-
1786
- type StringNumberMap = z.infer<typeof stringNumberMap>;
1787
- // type StringNumberMap = Map<string, number>
1788
- ```
1789
-
1790
- ## Sets
1791
-
1792
- ```ts
1793
- const numberSet = z.set(z.number());
1794
- type NumberSet = z.infer<typeof numberSet>;
1795
- // type NumberSet = Set<number>
1796
- ```
1797
-
1798
- Set schemas can be further constrained with the following utility methods.
1799
-
1800
- ```ts
1801
- z.set(z.string()).nonempty(); // must contain at least one item
1802
- z.set(z.string()).min(5); // must contain 5 or more items
1803
- z.set(z.string()).max(5); // must contain 5 or fewer items
1804
- z.set(z.string()).size(5); // must contain 5 items exactly
1805
- ```
1806
-
1807
- ## Intersections
1808
-
1809
- Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types.
1810
-
1811
- ```ts
1812
- const Person = z.object({
1813
- name: z.string(),
1814
- });
1815
-
1816
- const Employee = z.object({
1817
- role: z.string(),
1818
- });
1819
-
1820
- const EmployedPerson = z.intersection(Person, Employee);
1821
-
1822
- // equivalent to:
1823
- const EmployedPerson = Person.and(Employee);
1824
- ```
1825
-
1826
- Though in many cases, it is recommended to use `A.merge(B)` to merge two objects. The `.merge` method returns a new `ZodObject` instance, whereas `A.and(B)` returns a less useful `ZodIntersection` instance that lacks common object methods like `pick` and `omit`.
1827
-
1828
- ```ts
1829
- const a = z.union([z.number(), z.string()]);
1830
- const b = z.union([z.number(), z.boolean()]);
1831
- const c = z.intersection(a, b);
1832
-
1833
- type c = z.infer<typeof c>; // => number
1834
- ```
1835
-
1836
- <!-- Intersections in Zod are not smart. Whatever data you pass into `.parse()` gets passed into the two intersected schemas. Because Zod object schemas don't allow any unknown keys by default, there are some unintuitive behavior surrounding intersections of object schemas. -->
1837
-
1838
- <!--
1839
-
1840
- ``` ts
1841
- const A = z.object({
1842
- a: z.string(),
1843
- });
1844
-
1845
- const B = z.object({
1846
- b: z.string(),
1847
- });
1848
-
1849
- const AB = z.intersection(A, B);
1850
-
1851
- type Teacher = z.infer<typeof Teacher>;
1852
- // { id:string; name:string };
1853
- ``` -->
1854
-
1855
- ## Recursive types
1856
-
1857
- You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint".
1858
-
1859
- ```ts
1860
- const baseCategorySchema = z.object({
1861
- name: z.string(),
1862
- });
1863
-
1864
- type Category = z.infer<typeof baseCategorySchema> & {
1865
- subcategories: Category[];
1866
- };
1867
-
1868
- const categorySchema: z.ZodType<Category> = baseCategorySchema.extend({
1869
- subcategories: z.lazy(() => categorySchema.array()),
1870
- });
1871
-
1872
- categorySchema.parse({
1873
- name: "People",
1874
- subcategories: [
1875
- {
1876
- name: "Politicians",
1877
- subcategories: [
1878
- {
1879
- name: "Presidents",
1880
- subcategories: [],
1881
- },
1882
- ],
1883
- },
1884
- ],
1885
- }); // passes
1886
- ```
1887
-
1888
- Thanks to [crasite](https://github.com/crasite) for this example.
1889
-
1890
- ### ZodType with ZodEffects
1891
-
1892
- When using `z.ZodType` with `z.ZodEffects` (
1893
- [`.refine`](https://github.com/colinhacks/zod#refine),
1894
- [`.transform`](https://github.com/colinhacks/zod#transform),
1895
- [`preprocess`](https://github.com/colinhacks/zod#preprocess),
1896
- etc...
1897
- ), you will need to define the input and output types of the schema. `z.ZodType<Output, z.ZodTypeDef, Input>`
1898
-
1899
- ```ts
1900
- const isValidId = (id: string): id is `${string}/${string}` =>
1901
- id.split("/").length === 2;
1902
-
1903
- const baseSchema = z.object({
1904
- id: z.string().refine(isValidId),
1905
- });
1906
-
1907
- type Input = z.input<typeof baseSchema> & {
1908
- children: Input[];
1909
- };
1910
-
1911
- type Output = z.output<typeof baseSchema> & {
1912
- children: Output[];
1913
- };
1914
-
1915
- const schema: z.ZodType<Output, z.ZodTypeDef, Input> = baseSchema.extend({
1916
- children: z.lazy(() => schema.array()),
1917
- });
1918
- ```
1919
-
1920
- Thanks to [marcus13371337](https://github.com/marcus13371337) and [JoelBeeldi](https://github.com/JoelBeeldi) for this example.
1921
-
1922
- ### JSON type
1923
-
1924
- If you want to validate any JSON value, you can use the snippet below.
1925
-
1926
- ```ts
1927
- const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
1928
- type Literal = z.infer<typeof literalSchema>;
1929
- type Json = Literal | { [key: string]: Json } | Json[];
1930
- const jsonSchema: z.ZodType<Json> = z.lazy(() =>
1931
- z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
1932
- );
1933
-
1934
- jsonSchema.parse(data);
1935
- ```
1936
-
1937
- Thanks to [ggoodman](https://github.com/ggoodman) for suggesting this.
1938
-
1939
- ### Cyclical objects
1940
-
1941
- Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop in some cases.
1942
-
1943
- > To detect cyclical objects before they cause problems, consider [this approach](https://gist.github.com/colinhacks/d35825e505e635df27cc950776c5500b).
1944
-
1945
- ## Promises
1946
-
1947
- ```ts
1948
- const numberPromise = z.promise(z.number());
1949
- ```
1950
-
1951
- "Parsing" works a little differently with promise schemas. Validation happens in two parts:
1952
-
1953
- 1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with `.then` and `.catch` methods.).
1954
- 2. Zod uses `.then` to attach an additional validation step onto the existing Promise. You'll have to use `.catch` on the returned Promise to handle validation failures.
1955
-
1956
- ```ts
1957
- numberPromise.parse("tuna");
1958
- // ZodError: Non-Promise type: string
1959
-
1960
- numberPromise.parse(Promise.resolve("tuna"));
1961
- // => Promise<number>
1962
-
1963
- const test = async () => {
1964
- await numberPromise.parse(Promise.resolve("tuna"));
1965
- // ZodError: Non-number type: string
1966
-
1967
- await numberPromise.parse(Promise.resolve(3.14));
1968
- // => 3.14
1969
- };
1970
- ```
1971
-
1972
- <!-- #### Non-native promise implementations
1973
-
1974
- When "parsing" a promise, Zod checks that the passed value is an object with `.then` and `.catch` methods โ€” that's it. So you should be able to pass non-native Promises (Bluebird, etc) into `z.promise(...).parse` with no trouble. One gotcha: the return type of the parse function will be a _native_ `Promise` , so if you have downstream logic that uses non-standard Promise methods, this won't work. -->
1975
-
1976
- ## Instanceof
1977
-
1978
- You can use `z.instanceof` to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries.
1979
-
1980
- ```ts
1981
- class Test {
1982
- name: string;
1983
- }
1984
-
1985
- const TestSchema = z.instanceof(Test);
1986
-
1987
- const blob: any = "whatever";
1988
- TestSchema.parse(new Test()); // passes
1989
- TestSchema.parse(blob); // throws
1990
- ```
1991
-
1992
- ## Functions
1993
-
1994
- Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic".
1995
-
1996
- You can create a function schema with `z.function(args, returnType)` .
1997
-
1998
- ```ts
1999
- const myFunction = z.function();
2000
-
2001
- type myFunction = z.infer<typeof myFunction>;
2002
- // => ()=>unknown
2003
- ```
2004
-
2005
- Define inputs and outputs.
2006
-
2007
- ```ts
2008
- const myFunction = z
2009
- .function()
2010
- .args(z.string(), z.number()) // accepts an arbitrary number of arguments
2011
- .returns(z.boolean());
2012
-
2013
- type myFunction = z.infer<typeof myFunction>;
2014
- // => (arg0: string, arg1: number)=>boolean
2015
- ```
2016
-
2017
- <!--
2018
-
2019
- ``` ts
2020
- const args = z.tuple([z.string()]);
2021
-
2022
- const returnType = z.number();
2023
-
2024
- const myFunction = z.function(args, returnType);
2025
- type myFunction = z.infer<typeof myFunction>;
2026
- // => (arg0: string)=>number
2027
- ``` -->
2028
-
2029
- Function schemas have an `.implement()` method which accepts a function and returns a new function that automatically validates its inputs and outputs.
2030
-
2031
- ```ts
2032
- const trimmedLength = z
2033
- .function()
2034
- .args(z.string()) // accepts an arbitrary number of arguments
2035
- .returns(z.number())
2036
- .implement((x) => {
2037
- // TypeScript knows x is a string!
2038
- return x.trim().length;
2039
- });
2040
-
2041
- trimmedLength("sandwich"); // => 8
2042
- trimmedLength(" asdf "); // => 4
2043
- ```
2044
-
2045
- If you only care about validating inputs, just don't call the `.returns()` method. The output type will be inferred from the implementation.
2046
-
2047
- > You can use the special `z.void()` option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)
2048
-
2049
- ```ts
2050
- const myFunction = z
2051
- .function()
2052
- .args(z.string())
2053
- .implement((arg) => {
2054
- return [arg.length];
2055
- });
2056
-
2057
- myFunction; // (arg: string)=>number[]
2058
- ```
2059
-
2060
- Extract the input and output schemas from a function schema.
2061
-
2062
- ```ts
2063
- myFunction.parameters();
2064
- // => ZodTuple<[ZodString, ZodNumber]>
2065
-
2066
- myFunction.returnType();
2067
- // => ZodBoolean
2068
- ```
2069
-
2070
- <!-- `z.function()` accepts two arguments:
2071
-
2072
- * `args: ZodTuple` The first argument is a tuple (created with `z.tuple([...])` and defines the schema of the arguments to your function. If the function doesn't accept arguments, you can pass an empty tuple (`z.tuple([])`).
2073
- * `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema. -->
2074
-
2075
- ## Preprocess
2076
-
2077
- > Zod now supports primitive coercion without the need for `.preprocess()`. See the [coercion docs](#coercion-for-primitives) for more information.
2078
-
2079
- Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the [.transform docs](#transform).)
2080
-
2081
- But sometimes you want to apply some transform to the input _before_ parsing happens. A common use case: type coercion. Zod enables this with the `z.preprocess()`.
2082
-
2083
- ```ts
2084
- const castToString = z.preprocess((val) => String(val), z.string());
2085
- ```
2086
-
2087
- This returns a `ZodEffects` instance. `ZodEffects` is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms.
2088
-
2089
- ## Custom schemas
2090
-
2091
- You can create a Zod schema for any TypeScript type by using `z.custom()`. This is useful for creating schemas for types that are not supported by Zod out of the box, such as template string literals.
2092
-
2093
- ```ts
2094
- const px = z.custom<`${number}px`>((val) => {
2095
- return typeof val === "string" ? /^\d+px$/.test(val) : false;
2096
- });
2097
-
2098
- type px = z.infer<typeof px>; // `${number}px`
2099
-
2100
- px.parse("42px"); // "42px"
2101
- px.parse("42vw"); // throws;
2102
- ```
2103
-
2104
- If you don't provide a validation function, Zod will allow any value. This can be dangerous!
2105
-
2106
- ```ts
2107
- z.custom<{ arg: string }>(); // performs no validation
2108
- ```
2109
-
2110
- You can customize the error message and other options by passing a second argument. This parameter works the same way as the params parameter of [`.refine`](#refine).
2111
-
2112
- ```ts
2113
- z.custom<...>((val) => ..., "custom error message");
2114
- ```
2115
-
2116
- ## Schema methods
2117
-
2118
- All Zod schemas contain certain methods.
2119
-
2120
- ### `.parse`
2121
-
2122
- `.parse(data: unknown): T`
2123
-
2124
- Given any Zod schema, you can call its `.parse` method to check `data` is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.
2125
-
2126
- > IMPORTANT: The value returned by `.parse` is a _deep clone_ of the variable you passed in.
2127
-
2128
- ```ts
2129
- const stringSchema = z.string();
2130
-
2131
- stringSchema.parse("fish"); // => returns "fish"
2132
- stringSchema.parse(12); // throws error
2133
- ```
2134
-
2135
- ### `.parseAsync`
2136
-
2137
- `.parseAsync(data:unknown): Promise<T>`
2138
-
2139
- If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`.
2140
-
2141
- ```ts
2142
- const stringSchema = z.string().refine(async (val) => val.length <= 8);
2143
-
2144
- await stringSchema.parseAsync("hello"); // => returns "hello"
2145
- await stringSchema.parseAsync("hello world"); // => throws error
2146
- ```
2147
-
2148
- ### `.safeParse`
2149
-
2150
- `.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }`
2151
-
2152
- If you don't want Zod to throw errors when validation fails, use `.safeParse`. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.
2153
-
2154
- ```ts
2155
- stringSchema.safeParse(12);
2156
- // => { success: false; error: ZodError }
2157
-
2158
- stringSchema.safeParse("billie");
2159
- // => { success: true; data: 'billie' }
2160
- ```
2161
-
2162
- The result is a _discriminated union_, so you can handle errors very conveniently:
2163
-
2164
- ```ts
2165
- const result = stringSchema.safeParse("billie");
2166
- if (!result.success) {
2167
- // handle error then return
2168
- result.error;
2169
- } else {
2170
- // do something
2171
- result.data;
2172
- }
2173
- ```
2174
-
2175
- ### `.safeParseAsync`
2176
-
2177
- > Alias: `.spa`
2178
-
2179
- An asynchronous version of `safeParse`.
2180
-
2181
- ```ts
2182
- await stringSchema.safeParseAsync("billie");
2183
- ```
2184
-
2185
- For convenience, this has been aliased to `.spa`:
2186
-
2187
- ```ts
2188
- await stringSchema.spa("billie");
2189
- ```
2190
-
2191
- ### `.refine`
2192
-
2193
- `.refine(validator: (data:T)=>any, params?: RefineParams)`
2194
-
2195
- Zod lets you provide custom validation logic via _refinements_. (For advanced features like creating multiple issues and customizing error codes, see [`.superRefine`](#superrefine).)
2196
-
2197
- Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an integer or that a string is a valid email address.
2198
-
2199
- For example, you can define a custom validation check on _any_ Zod schema with `.refine` :
2200
-
2201
- ```ts
2202
- const myString = z.string().refine((val) => val.length <= 255, {
2203
- message: "String can't be more than 255 characters",
2204
- });
2205
- ```
2206
-
2207
- > โš ๏ธ Refinement functions should not throw. Instead they should return a falsy value to signal failure.
2208
-
2209
- #### Arguments
2210
-
2211
- As you can see, `.refine` takes two arguments.
2212
-
2213
- 1. The first is the validation function. This function takes one input (of type `T` โ€” the inferred type of the schema) and returns `any`. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.)
2214
- 2. The second argument accepts some options. You can use this to customize certain error-handling behavior:
2215
-
2216
- ```ts
2217
- type RefineParams = {
2218
- // override error message
2219
- message?: string;
2220
-
2221
- // appended to error path
2222
- path?: (string | number)[];
2223
-
2224
- // params object you can use to customize message
2225
- // in error map
2226
- params?: object;
2227
- };
2228
- ```
2229
-
2230
- For advanced cases, the second argument can also be a function that returns `RefineParams`.
2231
-
2232
- ```ts
2233
- const longString = z.string().refine(
2234
- (val) => val.length > 10,
2235
- (val) => ({ message: `${val} is not more than 10 characters` })
2236
- );
2237
- ```
2238
-
2239
- #### Customize error path
2240
-
2241
- ```ts
2242
- const passwordForm = z
2243
- .object({
2244
- password: z.string(),
2245
- confirm: z.string(),
2246
- })
2247
- .refine((data) => data.password === data.confirm, {
2248
- message: "Passwords don't match",
2249
- path: ["confirm"], // path of error
2250
- });
2251
-
2252
- passwordForm.parse({ password: "asdf", confirm: "qwer" });
2253
- ```
2254
-
2255
- Because you provided a `path` parameter, the resulting error will be:
2256
-
2257
- ```ts
2258
- ZodError {
2259
- issues: [{
2260
- "code": "custom",
2261
- "path": [ "confirm" ],
2262
- "message": "Passwords don't match"
2263
- }]
2264
- }
2265
- ```
2266
-
2267
- #### Asynchronous refinements
2268
-
2269
- Refinements can also be async:
2270
-
2271
- ```ts
2272
- const userId = z.string().refine(async (id) => {
2273
- // verify that ID exists in database
2274
- return true;
2275
- });
2276
- ```
2277
-
2278
- > โš ๏ธ If you use async refinements, you must use the `.parseAsync` method to parse data! Otherwise Zod will throw an error.
2279
-
2280
- #### Relationship to transforms
2281
-
2282
- Transforms and refinements can be interleaved:
2283
-
2284
- ```ts
2285
- z.string()
2286
- .transform((val) => val.length)
2287
- .refine((val) => val > 25);
2288
- ```
2289
-
2290
- <!-- Note that the `path` is set to `["confirm"]` , so you can easily display this error underneath the "Confirm password" textbox.
2291
-
2292
- ```ts
2293
- const allForms = z.object({ passwordForm }).parse({
2294
- passwordForm: {
2295
- password: "asdf",
2296
- confirm: "qwer",
2297
- },
2298
- });
2299
- ```
2300
-
2301
- would result in
2302
-
2303
- ```
2304
-
2305
- ZodError {
2306
- issues: [{
2307
- "code": "custom",
2308
- "path": [ "passwordForm", "confirm" ],
2309
- "message": "Passwords don't match"
2310
- }]
2311
- }
2312
- ``` -->
2313
-
2314
- ### `.superRefine`
2315
-
2316
- The `.refine` method is actually syntactic sugar atop a more versatile (and verbose) method called `superRefine`. Here's an example:
2317
-
2318
- ```ts
2319
- const Strings = z.array(z.string()).superRefine((val, ctx) => {
2320
- if (val.length > 3) {
2321
- ctx.addIssue({
2322
- code: z.ZodIssueCode.too_big,
2323
- maximum: 3,
2324
- type: "array",
2325
- inclusive: true,
2326
- message: "Too many items ๐Ÿ˜ก",
2327
- });
2328
- }
2329
-
2330
- if (val.length !== new Set(val).size) {
2331
- ctx.addIssue({
2332
- code: z.ZodIssueCode.custom,
2333
- message: `No duplicates allowed.`,
2334
- });
2335
- }
2336
- });
2337
- ```
2338
-
2339
- You can add as many issues as you like. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes.
2340
-
2341
- Normally refinements always create issues with a `ZodIssueCode.custom` error code, but with `superRefine` it's possible to throw issues of any `ZodIssueCode`. Each issue code is described in detail in the Error Handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md).
2342
-
2343
- #### Abort early
2344
-
2345
- By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the `fatal` flag to `ctx.addIssue` and return `z.NEVER`.
2346
-
2347
- ```ts
2348
- const schema = z.number().superRefine((val, ctx) => {
2349
- if (val < 10) {
2350
- ctx.addIssue({
2351
- code: z.ZodIssueCode.custom,
2352
- message: "should be >= 10",
2353
- fatal: true,
2354
- });
2355
-
2356
- return z.NEVER;
2357
- }
2358
-
2359
- if (val !== 12) {
2360
- ctx.addIssue({
2361
- code: z.ZodIssueCode.custom,
2362
- message: "should be twelve",
2363
- });
2364
- }
2365
- });
2366
- ```
2367
-
2368
- #### Type refinements
2369
-
2370
- If you provide a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) to `.refine()` or `.superRefine()`, the resulting type will be narrowed down to your predicate's type. This is useful if you are mixing multiple chained refinements and transformations:
2371
-
2372
- ```ts
2373
- const schema = z
2374
- .object({
2375
- first: z.string(),
2376
- second: z.number(),
2377
- })
2378
- .nullable()
2379
- .superRefine((arg, ctx): arg is { first: string; second: number } => {
2380
- if (!arg) {
2381
- ctx.addIssue({
2382
- code: z.ZodIssueCode.custom, // customize your issue
2383
- message: "object should exist",
2384
- });
2385
- }
2386
-
2387
- return z.NEVER; // The return value is not used, but we need to return something to satisfy the typing
2388
- })
2389
- // here, TS knows that arg is not null
2390
- .refine((arg) => arg.first === "bob", "`first` is not `bob`!");
2391
- ```
2392
-
2393
- > โš ๏ธ You **must** use `ctx.addIssue()` instead of returning a boolean value to indicate whether the validation passes. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes.
2394
-
2395
- ### `.transform`
2396
-
2397
- To transform data after parsing, use the `transform` method.
2398
-
2399
- ```ts
2400
- const stringToNumber = z.string().transform((val) => val.length);
2401
-
2402
- stringToNumber.parse("string"); // => 6
2403
- ```
2404
-
2405
- #### Chaining order
2406
-
2407
- Note that `stringToNumber` above is an instance of the `ZodEffects` subclass. It is NOT an instance of `ZodString`. If you want to use the built-in methods of `ZodString` (e.g. `.email()`) you must apply those methods _before_ any transforms.
2408
-
2409
- ```ts
2410
- const emailToDomain = z
2411
- .string()
2412
- .email()
2413
- .transform((val) => val.split("@")[1]);
2414
-
2415
- emailToDomain.parse("colinhacks@example.com"); // => example.com
2416
- ```
2417
-
2418
- #### Validating during transform
2419
-
2420
- The `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `transform` and `refine`.
2421
-
2422
- As with `.superRefine`, the transform function receives a `ctx` object with an `addIssue` method that can be used to register validation issues.
2423
-
2424
- ```ts
2425
- const numberInString = z.string().transform((val, ctx) => {
2426
- const parsed = parseInt(val);
2427
- if (isNaN(parsed)) {
2428
- ctx.addIssue({
2429
- code: z.ZodIssueCode.custom,
2430
- message: "Not a number",
2431
- });
2432
-
2433
- // This is a special symbol you can use to
2434
- // return early from the transform function.
2435
- // It has type `never` so it does not affect the
2436
- // inferred return type.
2437
- return z.NEVER;
2438
- }
2439
- return parsed;
2440
- });
2441
- ```
2442
-
2443
- #### Relationship to refinements
2444
-
2445
- Transforms and refinements can be interleaved. These will be executed in the order they are declared.
2446
-
2447
- ```ts
2448
- const nameToGreeting = z
2449
- .string()
2450
- .transform((val) => val.toUpperCase())
2451
- .refine((val) => val.length > 15)
2452
- .transform((val) => `Hello ${val}`)
2453
- .refine((val) => val.indexOf("!") === -1);
2454
- ```
2455
-
2456
- #### Async transforms
2457
-
2458
- Transforms can also be async.
2459
-
2460
- ```ts
2461
- const IdToUser = z
2462
- .string()
2463
- .uuid()
2464
- .transform(async (id) => {
2465
- return await getUserById(id);
2466
- });
2467
- ```
2468
-
2469
- > โš ๏ธ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error.
2470
-
2471
- ### `.default`
2472
-
2473
- You can use transforms to implement the concept of "default values" in Zod.
2474
-
2475
- ```ts
2476
- const stringWithDefault = z.string().default("tuna");
2477
-
2478
- stringWithDefault.parse(undefined); // => "tuna"
2479
- ```
2480
-
2481
- Optionally, you can pass a function into `.default` that will be re-executed whenever a default value needs to be generated:
2482
-
2483
- ```ts
2484
- const numberWithRandomDefault = z.number().default(Math.random);
2485
-
2486
- numberWithRandomDefault.parse(undefined); // => 0.4413456736055323
2487
- numberWithRandomDefault.parse(undefined); // => 0.1871840107401901
2488
- numberWithRandomDefault.parse(undefined); // => 0.7223408162401552
2489
- ```
2490
-
2491
- Conceptually, this is how Zod processes default values:
2492
-
2493
- 1. If the input is `undefined`, the default value is returned
2494
- 2. Otherwise, the data is parsed using the base schema
2495
-
2496
- ### `.describe`
2497
-
2498
- Use `.describe()` to add a `description` property to the resulting schema.
2499
-
2500
- ```ts
2501
- const documentedString = z
2502
- .string()
2503
- .describe("A useful bit of text, if you know what to do with it.");
2504
- documentedString.description; // A useful bit of textโ€ฆ
2505
- ```
2506
-
2507
- This can be useful for documenting a field, for example in a JSON Schema using a library like [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema)).
2508
-
2509
- ### `.catch`
2510
-
2511
- Use `.catch()` to provide a "catch value" to be returned in the event of a parsing error.
2512
-
2513
- ```ts
2514
- const numberWithCatch = z.number().catch(42);
2515
-
2516
- numberWithCatch.parse(5); // => 5
2517
- numberWithCatch.parse("tuna"); // => 42
2518
- ```
2519
-
2520
- Optionally, you can pass a function into `.catch` that will be re-executed whenever a default value needs to be generated. A `ctx` object containing the caught error will be passed into this function.
2521
-
2522
- ```ts
2523
- const numberWithRandomCatch = z.number().catch((ctx) => {
2524
- ctx.error; // the caught ZodError
2525
- return Math.random();
2526
- });
2527
-
2528
- numberWithRandomCatch.parse("sup"); // => 0.4413456736055323
2529
- numberWithRandomCatch.parse("sup"); // => 0.1871840107401901
2530
- numberWithRandomCatch.parse("sup"); // => 0.7223408162401552
2531
- ```
2532
-
2533
- Conceptually, this is how Zod processes "catch values":
2534
-
2535
- 1. The data is parsed using the base schema
2536
- 2. If the parsing fails, the "catch value" is returned
2537
-
2538
- ### `.optional`
2539
-
2540
- A convenience method that returns an optional version of a schema.
2541
-
2542
- ```ts
2543
- const optionalString = z.string().optional(); // string | undefined
2544
-
2545
- // equivalent to
2546
- z.optional(z.string());
2547
- ```
2548
-
2549
- ### `.nullable`
2550
-
2551
- A convenience method that returns a nullable version of a schema.
2552
-
2553
- ```ts
2554
- const nullableString = z.string().nullable(); // string | null
2555
-
2556
- // equivalent to
2557
- z.nullable(z.string());
2558
- ```
2559
-
2560
- ### `.nullish`
2561
-
2562
- A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both `undefined` and `null`. Read more about the concept of "nullish" [in the TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing).
2563
-
2564
- ```ts
2565
- const nullishString = z.string().nullish(); // string | null | undefined
2566
-
2567
- // equivalent to
2568
- z.string().nullable().optional();
2569
- ```
2570
-
2571
- ### `.array`
2572
-
2573
- A convenience method that returns an array schema for the given type:
2574
-
2575
- ```ts
2576
- const stringArray = z.string().array(); // string[]
2577
-
2578
- // equivalent to
2579
- z.array(z.string());
2580
- ```
2581
-
2582
- ### `.promise`
2583
-
2584
- A convenience method for promise types:
2585
-
2586
- ```ts
2587
- const stringPromise = z.string().promise(); // Promise<string>
2588
-
2589
- // equivalent to
2590
- z.promise(z.string());
2591
- ```
2592
-
2593
- ### `.or`
2594
-
2595
- A convenience method for [union types](#unions).
2596
-
2597
- ```ts
2598
- const stringOrNumber = z.string().or(z.number()); // string | number
2599
-
2600
- // equivalent to
2601
- z.union([z.string(), z.number()]);
2602
- ```
2603
-
2604
- ### `.and`
2605
-
2606
- A convenience method for creating intersection types.
2607
-
2608
- ```ts
2609
- const nameAndAge = z
2610
- .object({ name: z.string() })
2611
- .and(z.object({ age: z.number() })); // { name: string } & { age: number }
2612
-
2613
- // equivalent to
2614
- z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() }));
2615
- ```
2616
-
2617
- ### `.brand`
2618
-
2619
- `.brand<T>() => ZodBranded<this, B>`
2620
-
2621
- TypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same.
2622
-
2623
- ```ts
2624
- type Cat = { name: string };
2625
- type Dog = { name: string };
2626
-
2627
- const petCat = (cat: Cat) => {};
2628
- const fido: Dog = { name: "fido" };
2629
- petCat(fido); // works fine
2630
- ```
2631
-
2632
- In some cases, its can be desirable to simulate _nominal typing_ inside TypeScript. For instance, you may wish to write a function that only accepts an input that has been validated by Zod. This can be achieved with _branded types_ (AKA _opaque types_).
2633
-
2634
- ```ts
2635
- const Cat = z.object({ name: z.string() }).brand<"Cat">();
2636
- type Cat = z.infer<typeof Cat>;
2637
-
2638
- const petCat = (cat: Cat) => {};
2639
-
2640
- // this works
2641
- const simba = Cat.parse({ name: "simba" });
2642
- petCat(simba);
2643
-
2644
- // this doesn't
2645
- petCat({ name: "fido" });
2646
- ```
2647
-
2648
- Under the hood, this works by attaching a "brand" to the inferred type using an intersection type. This way, plain/unbranded data structures are no longer assignable to the inferred type of the schema.
2649
-
2650
- ```ts
2651
- const Cat = z.object({ name: z.string() }).brand<"Cat">();
2652
- type Cat = z.infer<typeof Cat>;
2653
- // {name: string} & {[symbol]: "Cat"}
2654
- ```
2655
-
2656
- Note that branded types do not affect the runtime result of `.parse`. It is a static-only construct.
2657
-
2658
- ### `.readonly`
2659
-
2660
- `.readonly() => ZodReadonly<this>`
2661
-
2662
- This method returns a `ZodReadonly` schema instance that parses the input using the base schema, then calls `Object.freeze()` on the result. The inferred type is also marked as `readonly`.
2663
-
2664
- ```ts
2665
- const schema = z.object({ name: z.string() }).readonly();
2666
- type schema = z.infer<typeof schema>;
2667
- // Readonly<{name: string}>
2668
-
2669
- const result = schema.parse({ name: "fido" });
2670
- result.name = "simba"; // error
2671
- ```
2672
-
2673
- The inferred type uses TypeScript's built-in readonly types when relevant.
2674
-
2675
- ```ts
2676
- z.array(z.string()).readonly();
2677
- // readonly string[]
2678
-
2679
- z.tuple([z.string(), z.number()]).readonly();
2680
- // readonly [string, number]
2681
-
2682
- z.map(z.string(), z.date()).readonly();
2683
- // ReadonlyMap<string, Date>
2684
-
2685
- z.set(z.string()).readonly();
2686
- // ReadonlySet<string>
2687
- ```
2688
-
2689
- ### `.pipe`
2690
-
2691
- Schemas can be chained into validation "pipelines". It's useful for easily validating the result after a `.transform()`:
2692
-
2693
- ```ts
2694
- z.string()
2695
- .transform((val) => val.length)
2696
- .pipe(z.number().min(5));
2697
- ```
2698
-
2699
- The `.pipe()` method returns a `ZodPipeline` instance.
2700
-
2701
- #### You can use `.pipe()` to fix common issues with `z.coerce`.
2702
-
2703
- You can constrain the input to types that work well with your chosen coercion. Then use `.pipe()` to apply the coercion.
2704
-
2705
- without constrained input:
2706
-
2707
- ```ts
2708
- const toDate = z.coerce.date();
2709
-
2710
- // works intuitively
2711
- console.log(toDate.safeParse("2023-01-01").success); // true
2712
-
2713
- // might not be what you want
2714
- console.log(toDate.safeParse(null).success); // true
2715
- ```
2716
-
2717
- with constrained input:
2718
-
2719
- ```ts
2720
- const datelike = z.union([z.number(), z.string(), z.date()]);
2721
- const datelikeToDate = datelike.pipe(z.coerce.date());
2722
-
2723
- // still works intuitively
2724
- console.log(datelikeToDate.safeParse("2023-01-01").success); // true
2725
-
2726
- // more likely what you want
2727
- console.log(datelikeToDate.safeParse(null).success); // false
2728
- ```
2729
-
2730
- You can also use this technique to avoid coercions that throw uncaught errors.
2731
-
2732
- without constrained input:
2733
-
2734
- ```ts
2735
- const toBigInt = z.coerce.bigint();
2736
-
2737
- // works intuitively
2738
- console.log(toBigInt.safeParse("42")); // true
2739
-
2740
- // probably not what you want
2741
- console.log(toBigInt.safeParse(null)); // throws uncaught error
2742
- ```
2743
-
2744
- with constrained input:
2745
-
2746
- ```ts
2747
- const toNumber = z.number().or(z.string()).pipe(z.coerce.number());
2748
- const toBigInt = z.bigint().or(toNumber).pipe(z.coerce.bigint());
2749
-
2750
- // still works intuitively
2751
- console.log(toBigInt.safeParse("42").success); // true
2752
-
2753
- // error handled by zod, more likely what you want
2754
- console.log(toBigInt.safeParse(null).success); // false
2755
- ```
2756
-
2757
- ## Guides and concepts
2758
-
2759
- ### Type inference
2760
-
2761
- You can extract the TypeScript type of any schema with `z.infer<typeof mySchema>` .
2762
-
2763
- ```ts
2764
- const A = z.string();
2765
- type A = z.infer<typeof A>; // string
2766
-
2767
- const u: A = 12; // TypeError
2768
- const u: A = "asdf"; // compiles
2769
- ```
2770
-
2771
- **What about transforms?**
2772
-
2773
- In reality each Zod schema internally tracks **two** types: an input and an output. For most schemas (e.g. `z.string()`) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance `z.string().transform(val => val.length)` has an input of `string` and an output of `number`.
2774
-
2775
- You can separately extract the input and output types like so:
2776
-
2777
- ```ts
2778
- const stringToNumber = z.string().transform((val) => val.length);
2779
-
2780
- // โš ๏ธ Important: z.infer returns the OUTPUT type!
2781
- type input = z.input<typeof stringToNumber>; // string
2782
- type output = z.output<typeof stringToNumber>; // number
2783
-
2784
- // equivalent to z.output!
2785
- type inferred = z.infer<typeof stringToNumber>; // number
2786
- ```
2787
-
2788
- ### Writing generic functions
2789
-
2790
- With TypeScript generics, you can write reusable functions that accept Zod schemas as parameters. This enables you to create custom validation logic, schema transformations, and more, while maintaining type safety and inference.
2791
-
2792
- When attempting to write a function that accepts a Zod schema as an input, it's tempting to try something like this:
2793
-
2794
- ```ts
2795
- function inferSchema<T>(schema: z.ZodType<T>) {
2796
- return schema;
2797
- }
2798
- ```
2799
-
2800
- This approach is incorrect, and limits TypeScript's ability to properly infer the argument. No matter what you pass in, the type of `schema` will be an instance of `ZodType`.
2801
-
2802
- ```ts
2803
- inferSchema(z.string());
2804
- // => ZodType<string>
2805
- ```
2806
-
2807
- This approach loses type information, namely _which subclass_ the input actually is (in this case, `ZodString`). That means you can't call any string-specific methods like `.min()` on the result of `inferSchema`.
2808
-
2809
- A better approach is to infer _the schema as a whole_ instead of merely its inferred type. You can do this with a utility type called `z.ZodTypeAny`.
2810
-
2811
- ```ts
2812
- function inferSchema<T extends z.ZodTypeAny>(schema: T) {
2813
- return schema;
2814
- }
2815
-
2816
- inferSchema(z.string());
2817
- // => ZodString
2818
- ```
2819
-
2820
- > `ZodTypeAny` is just a shorthand for `ZodType<any, any, any>`, a type that is broad enough to match any Zod schema.
2821
-
2822
- The Result is now fully and properly typed, and the type system can infer the specific subclass of the schema.
2823
-
2824
- #### Inferring the inferred type
2825
-
2826
- If you follow the best practice of using `z.ZodTypeAny` as the generic parameter for your schema, you may encounter issues with the parsed data being typed as `any` instead of the inferred type of the schema.
2827
-
2828
- ```ts
2829
- function parseData<T extends z.ZodTypeAny>(data: unknown, schema: T) {
2830
- return schema.parse(data);
2831
- }
2832
-
2833
- parseData("sup", z.string());
2834
- // => any
2835
- ```
2836
-
2837
- Due to how TypeScript inference works, it is treating `schema` like a `ZodTypeAny` instead of the inferred type. You can fix this with a type cast using `z.infer`.
2838
-
2839
- ```ts
2840
- function parseData<T extends z.ZodTypeAny>(data: unknown, schema: T) {
2841
- return schema.parse(data) as z.infer<T>;
2842
- // ^^^^^^^^^^^^^^ <- add this
2843
- }
2844
-
2845
- parseData("sup", z.string());
2846
- // => string
2847
- ```
2848
-
2849
- #### Constraining allowable inputs
2850
-
2851
- The `ZodType` class has three generic parameters.
2852
-
2853
- ```ts
2854
- class ZodType<
2855
- Output = any,
2856
- Def extends ZodTypeDef = ZodTypeDef,
2857
- Input = Output
2858
- > { ... }
2859
- ```
2860
-
2861
- By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function:
2862
-
2863
- ```ts
2864
- function makeSchemaOptional<T extends z.ZodType<string>>(schema: T) {
2865
- return schema.optional();
2866
- }
2867
-
2868
- makeSchemaOptional(z.string());
2869
- // works fine
2870
-
2871
- makeSchemaOptional(z.number());
2872
- // Error: 'ZodNumber' is not assignable to parameter of type 'ZodType<string, ZodTypeDef, string>'
2873
- ```
2874
-
2875
- ### Error handling
2876
-
2877
- Zod provides a subclass of Error called `ZodError`. ZodErrors contain an `issues` array containing detailed information about the validation problems.
2878
-
2879
- ```ts
2880
- const result = z
2881
- .object({
2882
- name: z.string(),
2883
- })
2884
- .safeParse({ name: 12 });
2885
-
2886
- if (!result.success) {
2887
- result.error.issues;
2888
- /* [
2889
- {
2890
- "code": "invalid_type",
2891
- "expected": "string",
2892
- "received": "number",
2893
- "path": [ "name" ],
2894
- "message": "Expected string, received number"
2895
- }
2896
- ] */
2897
- }
2898
- ```
2899
-
2900
- > For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md)
2901
-
2902
- Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third-party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error)
2903
-
2904
- ### Error formatting
2905
-
2906
- You can use the `.format()` method to convert this error into a nested object.
2907
-
2908
- ```ts
2909
- const result = z
2910
- .object({
2911
- name: z.string(),
2912
- })
2913
- .safeParse({ name: 12 });
2914
-
2915
- if (!result.success) {
2916
- const formatted = result.error.format();
2917
- /* {
2918
- name: { _errors: [ 'Expected string, received number' ] }
2919
- } */
2920
-
2921
- formatted.name?._errors;
2922
- // => ["Expected string, received number"]
2923
- }
2924
- ```
2925
-
2926
- ## Comparison
2927
-
2928
- There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience.
2929
-
2930
- <!-- The table below summarizes the feature differences. Below the table there are more involved discussions of certain alternatives, where necessary. -->
2931
-
2932
- <!-- | Feature | [Zod](https://github.com/colinhacks) | [Joi](https://github.com/hapijs/joi) | [Yup](https://github.com/jquense/yup) | [io-ts](https://github.com/gcanti/io-ts) | [Runtypes](https://github.com/pelotom/runtypes) | [ow](https://github.com/sindresorhus/ow) | [class-validator](https://github.com/typestack/class-validator) |
2933
- | ---------------------------------------------------------------------------------------------------------------------- | :-----------------------------: | :----------------------------------: | :-----------------------------------: | :--------------------------------------: | :---------------------------------------------: | :--------------------------------------: | :-------------------------------------------------------------: |
2934
- | <abbr title='Any ability to extract a TypeScript type from a validator instance counts.'>Type inference</abbr> | ๐ŸŸข | ๐Ÿ”ด | ๐ŸŸข | ๐ŸŸข | ๐ŸŸข | ๐ŸŸข | ๐ŸŸข |
2935
- | <abbr title="Yup's inferred types are incorrect in certain cases, see discussion below.">Correct type inference</abbr> | ๐ŸŸข | ๐Ÿ”ด | ๐Ÿ”ด | ๐ŸŸข | ๐ŸŸข | ๐ŸŸข | ๐ŸŸข |
2936
-
2937
- <abbr title="number, string, boolean, null, undefined">Primitive Types</abbr>
2938
- <abbr title="Includes any checks beyond 'Is this a string?', e.g. min/max length, isEmail, isURL, case checking, etc.">String Validation</abbr>
2939
- <abbr title="Includes any checks beyond 'Is this a number?', e.g. min/max, isPositive, integer vs float, etc.">Number Validation</abbr>
2940
- Dates
2941
-
2942
- Primitive Literals
2943
- Object Literals
2944
- Tuple Literals
2945
- Objects
2946
- Arrays
2947
- Non-empty arrays
2948
- Unions
2949
- Optionals
2950
- Nullable
2951
- Enums
2952
- Enum Autocomplete
2953
- Intersections
2954
- Object Merging
2955
- Tuples
2956
- Recursive Types
2957
- Function Schemas
2958
-
2959
- <abbr title="For instance, Yup allows custom error messages with the syntax yup.number().min(5, 'Number must be more than 5!')">Validation Messages</abbr>
2960
- Immutable instances
2961
- Type Guards
2962
- Validity Checking
2963
- Casting
2964
- Default Values
2965
- Rich Errors
2966
- Branded -->
2967
-
2968
- <!-- - Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
2969
-
2970
- * Missing nonempty arrays with proper typing (`[T, ...T[]]`)
2971
- * Missing lazy/recursive types
2972
- * Missing promise schemas
2973
- * Missing function schemas
2974
- * Missing union & intersection schemas
2975
- * Missing support for parsing cyclical data (maybe)
2976
- * Missing error customization -->
2977
-
2978
- ### Joi
2979
-
2980
- [https://github.com/hapijs/joi](https://github.com/hapijs/joi)
2981
-
2982
- Doesn't support static type inference ๐Ÿ˜•
2983
-
2984
- ### Yup
2985
-
2986
- [https://github.com/jquense/yup](https://github.com/jquense/yup)
2987
-
2988
- Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript.
2989
-
2990
- - Supports casting and transforms
2991
- - All object fields are optional by default
2992
- <!-- - Missing nonempty arrays with proper typing (`[T, ...T[]]`) -->
2993
- - Missing promise schemas
2994
- - Missing function schemas
2995
- - Missing union & intersection schemas
2996
-
2997
- <!-- ยนYup has a strange interpretation of the word `required`. Instead of meaning "not undefined", Yup uses it to mean "not empty". So `yup.string().required()` will not accept an empty string, and `yup.array(yup.string()).required()` will not accept an empty array. Instead, Yup us Zod arrays there is a dedicated `.nonempty()` method to indicate this, or you can implement it with a custom refinement. -->
2998
-
2999
- ### io-ts
3000
-
3001
- [https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts)
3002
-
3003
- io-ts is an excellent library by gcanti. The API of io-ts heavily inspired the design of Zod.
3004
-
3005
- In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts:
3006
-
3007
- ```ts
3008
- import * as t from "io-ts";
3009
-
3010
- const A = t.type({
3011
- foo: t.string,
3012
- });
3013
-
3014
- const B = t.partial({
3015
- bar: t.number,
3016
- });
3017
-
3018
- const C = t.intersection([A, B]);
3019
-
3020
- type C = t.TypeOf<typeof C>;
3021
- // returns { foo: string; bar?: number | undefined }
3022
- ```
3023
-
3024
- You must define the required and optional props in separate object validators, pass the optionals through `t.partial` (which marks all properties as optional), then combine them with `t.intersection` .
3025
-
3026
- Consider the equivalent in Zod:
3027
-
3028
- ```ts
3029
- const C = z.object({
3030
- foo: z.string(),
3031
- bar: z.number().optional(),
3032
- });
3033
-
3034
- type C = z.infer<typeof C>;
3035
- // returns { foo: string; bar?: number | undefined }
3036
- ```
3037
-
3038
- This more declarative API makes schema definitions vastly more concise.
3039
-
3040
- `io-ts` also requires the use of gcanti's functional programming library `fp-ts` to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on `fp-ts` necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts and the `fp-ts` nomenclature to use the library.
3041
-
3042
- - Supports codecs with serialization & deserialization transforms
3043
- - Supports branded types
3044
- - Supports advanced functional programming, higher-kinded types, `fp-ts` compatibility
3045
- - Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
3046
- - Missing nonempty arrays with proper typing (`[T, ...T[]]`)
3047
- - Missing promise schemas
3048
- - Missing function schemas
3049
-
3050
- ### Runtypes
3051
-
3052
- [https://github.com/runtypes/runtypes](https://github.com/runtypes/runtypes)
3053
-
3054
- Runtypes is focused on ergonomics, with good type inference support.
3055
-
3056
- - Supports "pattern matching": computed properties that distribute over unions
3057
- - Supports branded types
3058
- - Supports template literals
3059
- - Supports conformance to predefined static types
3060
- - Missing object methods: (deepPartial, merge)
3061
- - Missing promise schemas
3062
- - Missing error customization
3063
-
3064
- ### Ow
3065
-
3066
- [https://github.com/sindresorhus/ow](https://github.com/sindresorhus/ow)
3067
-
3068
- Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping with TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. `int32Array` , see full list in their README).
3069
-
3070
- If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream.
3071
-
3072
- ## Changelog
3073
-
3074
- View the changelog at [CHANGELOG.md](CHANGELOG.md)