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