Skip to main content

Command Palette

Search for a command to run...

Exploring Zod: A Comprehensive Guide

Updated
3 min read
Exploring Zod: A Comprehensive Guide
D

I am a Software Engineer with 3+ years of experience, currently at P360. I have a passion for creating intuitive web interfaces and actively contribute to tech communities as the Organizer of GDG Siliguri, ex-Microsoft Learn Student Ambassador, and former Hack Club Lead. As a tech speaker, I’ve presented at events like FrontendDays Siliguri, GDG Bhopal, and Azure DevDay. I’m also passionate about hackathons and open-source: Smart India Hackathon 2020 winner, HacktoberFest contributor, and mentor to the winning team of SIH 2022.

Introduction

In the world of TypeScript, sometimes, the Typescript validations are not enough for us. In those situations, we want more control over the validations to make our code more robust. This is where Zod comes into the picture.

What is Zod?

Zod is a TypeScript-first schema declaration and validation library. It was created and developed by Vercel. It aims to make it easy for developers to define, validate and transform the data structures.

Getting Started With Zod

First, create a TypeScript project and then install Zod with npm by using the following command:

npm install zod

If you are using yarn, use the following command:

yarn add zod

If you are using pnpm, use the following command:

pnpm add zod

Also, make sure that you are using TypeScript 4.5+ and you enable strict mode in your tsconfig.json file.

// tsconfig.json
{
  // ...
  "compilerOptions": {
    // ...
    "strict": true
  }
}

Then, create a typescript file called index.ts and import the z object from the zod.

import { z } from 'zod';

This z helps you to define your schemas.

import { z } from 'zod';

const ageSchema = z.number();

ageSchema.parse(12); // it will works fine
ageSchema.parse('hello'); // this will throws an error from zod

For the ageSchema.parse('hello') method call, you will get an error from zod. It will look like this:

Error: [
{
"code": "invalid_type",
"expected": "number",
"received": "string",
"path": [],
"message": "Expected number, received string"
}
]

If you don't want Zod to throw an error, then use safeParse() instead of parse()

Deep Dive into Zod

In Zod, you can define the schemas for your data. Then, these schemas will do all the validation work for you. In Zod, there are a lot of primitive types available:

import { z } from 'zod';

// primitive types
z.number();
z.string();
z.bigint();
z.boolean();
z.date();
z.symbol();

// any types
z.any();
z.unknown();

// empty types
z.undefined();
z.null();
z.void();

// never type allows no value
z.never();

Now you may be thinking, I can also do this using TypeScript. What Zod can do more? You can also chain validator functions to enforce more strictness in your schemas:

import { z } from 'zod';

const nameSchema = z.string().max(5);
const emailSchema = z.email();
const emojiSchema = z.string().emoji();

After learning this much you must be like:

Wow Image

But I have more for you.

Real World Zod Use Case:

Let's say you want to build a User Register page. Here, you can use Zod to make the validation more strict. Example:

import { z } from 'zod';

const userSchema = z.object({
 firstName: z.string().nonempty(),
 lastName: z.string().optional(),
 email: z.string().email('Invalid email format').required('Email is required'),
 password: z.string().min(8, 'Password must be at least 8 characters').max(32).required()
});

// sample form data
const formData = {
 firstName: 'John',
 lastName: 'Doe',
 email: 'johndoe@gmail.com',
 password: 'john123'
};

// validate form data against userSchema
try {
 const parseData = userSchema.parse(formData);
 console.log('Validation Successful: ', formData);
 // if data is valid, then proceed with register
} catch(error) {
 if(error instanceof ZodError) {
  console.error('Validation failed. Errors:', error.errors);
 } else {
  console.error('Unexpected error during validation:', error.message);
 }
}

Conclusion

Zod is a powerful and intuitive library that enhances the TypeScript development experience by providing a seamless way to make the code more robust. Head over to zod.dev for the official documentation, tutorials, and examples

More from this blog

D

Debajit Mallick's Blog

19 posts

I am a Software Engineer with 2+ years of experience. Currently, I am working at P360 as a Software Engineer. My expertise is in Frontend Web Development.

I am very active in technical communities. I am the Organizer of GDG Siliguri, Ex β-MLSA, Ex Hack Club Lead, and Ex GSSOC Ambassador.

Also, I am a Tech Speaker too. I have given technical talks at many events like FrontendDays Siliguri, GDG Bhopal, GDSC WOW KOLKATA, JWOC, Azure Devday, Hack Club SIT, GirlScript Siliguri, GDSC SIT, Codecademy Frontend Marathon and many more.

I also like to participate in Hackathons and Open Source events. I won the Smart India Hackathon 2020 and contributed to HacktoberFest 2019, HacktoberFest 2020, JWOC and GWOC. Also, I mentored a team for Smart India Hackathon 2022 that later won the Hackathon.