Okay, if you don't known what that hell is Zod, I'll explain briefly
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.
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.
Without delay and straight to the point...
Suppose you have a field in your request that should only be validated if another field is also sent, how can I do that using Zod?
Piece of cake dude!
import { z } from 'zod'
const toy = z.object({
name: z.number().optional(),
color: z.string().optional(),
})
.refine(schema => schema.color ? !!schema.name : true, {
message: 'name is required when you send color on request'
})
in this case, if the color is sent through refine, we can validate if we have the name in the request as well.
credits to the master Pinoti 🍻
Top comments (0)