diff --git a/README.md b/README.md index 46a4544..8c1bb3c 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). -_1360 TILs and counting..._ +_1361 TILs and counting..._ --- @@ -1612,6 +1612,7 @@ _1360 TILs and counting..._ - [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) - [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) ## Usage diff --git a/zod/set-custom-error-message-for-nonempty-array.md b/zod/set-custom-error-message-for-nonempty-array.md new file mode 100644 index 0000000..bef8616 --- /dev/null +++ b/zod/set-custom-error-message-for-nonempty-array.md @@ -0,0 +1,57 @@ +# Set Custom Error Message For Nonempty Array + +Let's say we have the following schema that represents a team: + +```typescript +const TeamSchema = z.object({ + name: z.string(), + members: z.array( + z.object({ firstName: z.string(), lastName: z.string() }) + ) +}) +``` + +If we want to enforce that a team must contain at least _one_ member in order +to be valid, we can chain the `nonempty` function on the `members` array. + +```typescript +const TeamSchema = z.object({ + name: z.string(), + members: z.array( + z.object({ firstName: z.string(), lastName: z.string() }) + ).nonempty() +}) +``` + +Then we can set a custom error message for when that _nonempty_ requirement is +violated by adding an object argument with a `message`: + +```typescript +const TeamSchema = z.object({ + name: z.string(), + members: z.array( + z.object({ firstName: z.string(), lastName: z.string() }) + ).nonempty({ + message: 'A team must contain at least one member' + }) +}) +``` + +Here is that schema in action, not the `message` in the error: + +```typescript +TeamSchema.parse({ name: 'A-Team', members: [] }) +// Error: [{ +// "code": "too_small", +// "minimum": 1, +// "type": "array", +// "inclusive": true, +// "exact": false, +// "message": "A team must contain at least one member", +// "path": [ +// "members" +// ] +// }] +``` + +[source](https://github.com/colinhacks/zod#nonempty)