DEV Community

Marcos Henrique
Marcos Henrique

Posted on

11 3 1

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 🍻

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay