Data Validation Using Zod

Data Validation Using Zod

Introduction

Tired of writing your own complex and long data validation code? We've all been there. Writing you own data validation code can be tedious and difficult to maintain. Thankfully, there is a library out there called Zod which makes this process of data validation easier than ever before. From frontend form validation to robust database schema design, developers are embracing Zod for data validation.

But is it safe? Is it worth the hype? Let's find out.

💡
This blog will cover the basics of Zod. If you seek the understanding of advanced functions, I highly recommend you to visit their documentation.

Basic Validation

Let's see how Zod validates datatype efficiently as compared to manual validation. Use the command written below to install zod into your node project.

npm i zod

This is how we manually validate a string and other datatypes as well.

This is how Zod does it. The safeParse function takes the datatype as a parameter to validate it and returns an object with the format {success: true, data:'Input datatype'}

{success: false, error:[Getter]} when the desired datatype is not provided.

Refer this table for basic datatype validation.

DatatypesFunction
Stringz.string()
Numberz.number()
Booleanz.boolean()
Datez.date()
Objectz.object({ name: z.string() })

In the above example we just saw how Zod validates the data efficiently as compared to manual validation. It is not just limited to validate datatypes but also various other inputs.

From emails to contact number, Zod can validate almost every input.

Let's take a form for example and let us validate it's basic inputs. We will validate name, email, password and contact number using Zod.

The above code validates basic form inputs and eliminates the tedious process of writing manual validation.

Conclusion

In summary, Zod is a great tool for checking if data is correct in computer programs. It's easy to use and does a lot of different checks to make sure your data is good to go. Using Zod can help make your programs better and catch mistakes before they cause problems. Whether you're making websites or other types of software, Zod can make sure your data is in good shape.

Check out my other blog where I have displayed the application of Shadcn, a component collection which is gaining popularity.
Shadcn blog

Celebrity gif. Jeff Bridges raises his hand and says, “Adios.” Then, he runs out the door. Text, “Adios.”