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 🍻

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️