DEV Community

Marcos Henrique
Marcos Henrique

Posted on

Validate related schema attributes with Zod

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...

DiCaprio point to somewhere
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!

A funny dude saying Piece of cake

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'
})
Enter fullscreen mode Exit fullscreen mode

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 🍻

Discussion (0)