1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Get Readable Errors From Schema Parse as a Zod TIL

This commit is contained in:
jbranchaud
2024-02-27 19:47:32 -06:00
parent d0690a3b5a
commit 24278989d8
2 changed files with 54 additions and 1 deletions

View File

@@ -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)

View File

@@ -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)