From 24278989d837d26590558ac71fa35f3109368af4 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 27 Feb 2024 19:47:32 -0600 Subject: [PATCH] Add Get Readable Errors From Schema Parse as a Zod TIL --- README.md | 3 +- zod/get-readable-errors-from-schema-parse.md | 52 ++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 zod/get-readable-errors-from-schema-parse.md diff --git a/README.md b/README.md index c2940ea..6e8ee9e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1381 TILs and counting..._ +_1382 TILs and counting..._ --- @@ -1639,6 +1639,7 @@ _1381 TILs and counting..._ - [Check If An Object Is Empty With Zod](zod/check-if-an-object-is-empty-with-zod.md) - [Create A Schema That Matches On Any Object](zod/create-a-schema-that-matches-on-any-object.md) - [Create Union Type Of Nearly Identical Objects](zod/create-union-type-of-nearly-identical-objects.md) +- [Get Readable Errors From Schema Parse](zod/get-readable-errors-from-schema-parse.md) - [Incorporate Existing Type Into Zod Schema](zod/incorporate-existing-type-into-zod-schema.md) - [Set Custom Error Message For Nonempty Array](zod/set-custom-error-message-for-nonempty-array.md) diff --git a/zod/get-readable-errors-from-schema-parse.md b/zod/get-readable-errors-from-schema-parse.md new file mode 100644 index 0000000..8a88d7a --- /dev/null +++ b/zod/get-readable-errors-from-schema-parse.md @@ -0,0 +1,52 @@ +# Get Readable Errors From Schema Parse + +Let's say we have the following schema for validating the data used to create a +new post record: + +```typescript +const NewPostSchema = z.object({ + title: z.string().min(1, "Title is required"), + slug: z.string().min(1, "Slug is required"), + markdown: z.string().min(1, "Markdown is required"), +}); +``` + +When we (safe) parse some incoming user input with that schema and, for +example, one of the fields is empty, then the validation will fail and we'll +get some errors. + +```typescript +const result = NewPostSchema.safeParse(userInput) + +if(!result.success) { + result.error; + // ZodError: [ + // { + // "code": "too_small", + // "minimum": 1, + // "type": "string", + // "inclusive": true, + // "exact": false, + // "message": "Slug is required", + // "path": [ + // "slug" + // ] + // } + // ] +} +``` + +That packs a lot of information. But if we are just trying to get something +minimal and actionable we can show to a user, we might want to flatten the +errors: + +```typescript +const result = NewPostSchema.safeParse(userInput) + +if(!result.success) { + result.error.flatten().fieldErrors; + // { slug: [ 'Slug is required' ] } +} +``` + +[source](https://github.com/colinhacks/zod/blob/master/ERROR_HANDLING.md#flattening-errors)