Zod For Data Validation In TypeScript
If you’re writing any sort of web application online, chances are that you are accepting some form of user data. All data is evil. You should validate everything, and if you’re using TypeScript, there’s just a great solution you’d love to work with.
What is Zod?
Zod is like a superhero for data validation. You can think of it as your trusty sidekick, always ready to swoop in and protect your code from bad data. With Zod, you can define data schemas with ease, and then validate your data against those schemas to ensure it meets your requirements.
Superpowers of Zod
Zod has a ton of superpowers that make it a popular choice among TypeScript developers. Here are just a few of its most notable features:
Static Typing
Zod is built on top of TypeScript, so it takes full advantage of TypeScript’s static type system to provide compile-time guarantees that your code is handling data correctly. This can save you a ton of time and headaches by catching errors early in the development process.
Schema Validation
Zod makes it easy to define complex data schemas with a wide range of schema types such as strings, numbers, booleans, arrays, objects, and more. You can even define custom schemas and validators to suit your specific use case.
Custom Error Messages
Zod provides an API for customizing error messages. This allows you to provide more informative error messages that help end-users understand what went wrong during validation. No more cryptic error messages that leave users scratching their heads!
Nesting
Zod allows for nesting of schemas, which makes it easy to build complex validation logic. This feature is especially useful when working with nested objects and arrays.
Async Validation
Zod provides an API for performing async validation. This allows you to validate data that requires async operations such as network requests. No more waiting for data to come back before you can validate it!
Lightweight
Zod is a lightweight library with a small API surface. This makes it easy to learn and use. You don’t need to be a superhero to use Zod – anyone can pick it up and start using it in their projects.
How to Use Zod to Save the World (of Data Validation)
To get started with Zod, you’ll need to install it first. You can do this with npm or yarn:
npm install zod
# or
yarn add zod
Code language: JavaScript (javascript)
Once you have Zod installed, you can import it into your TypeScript project:
import { z } from 'zod'
Code language: JavaScript (javascript)
Defining Schemas – The Secret Weapon
Zod’s secret weapon is its ability to define schemas with ease. To define a schema with Zod, you can use the z.schema
method. Here’s an example:
const schema = z.schema({
name: z.string(),
age: z.number(),
email: z.string().email(),
})
Code language: JavaScript (javascript)
In this example, we’ve defined a schema with three properties: name
, age
, and email
. The email
property uses the .email()
method to ensure that the value is a valid email address. It’s like a shield for your data – protecting it from bad actors and bad inputs!
Validating Data – Your Secret Weapon in Action
Once you’ve defined a schema, you can use it to validate data. Here’s an example:
const data = {
name: 'Bruce Wayne',
age: 35,
email: '[email protected]
};
try {
schema.parse(data)
console.log('Data is valid')
} catch (error) {
console.error('Validation failed:', error)
}
Code language: JavaScript (javascript)
In this example, we’ve defined an object data
that matches the schema we defined earlier. We then use the .parse()
method to validate the data against the schema. If the data is valid, the console.log()
statement will be executed. Otherwise, the console.error()
statement will be executed with the validation error. It’s like having X-ray vision for your data!
Customizing Error Messages – Your Secret Weapon with a Personal Touch
Zod allows for customizing error messages to provide more informative messages to end-users. Here’s an example:
const schema = z.schema({
name: z.string().min(3, { message: 'Name must be at least 3 characters' }),
age: z.number().max(120, { message: 'Age cannot be greater than 120' }),
email: z.string().email({ message: 'Email must be a valid email address' }),
})
Code language: JavaScript (javascript)
In this example, we’ve customized the error messages for the name
, age
, and email
properties. This will ensure that end-users get more informative error messages when validation fails. It’s like adding a personal touch to your data validation!
Nesting Objects with Zod
Zod allows for nesting schemas, which allows for building complex validation logic. Here’s an example:
const addressSchema = z.object({
street: z.string(),
city: z.string(),
state: z.string().length(2),
zip: z.string().length(5),
});
const userSchema = z.schema({
name: z.string(),
age: z.number(),
email: z.string().email(),
address: addressSchema,
});
Code language: JavaScript (javascript)
In this example, we’ve defined two schemas: addressSchema
and userSchema
. The userSchema
schema has a property address
that uses the addressSchema
schema. This allows for validating nested objects. It’s like having a superpower that can handle even the most complex data structures!
Async Validation with Zod
Zod provides an API for performing async validation. Here’s an example:
const schema = z.object({
id: z.string().refine(async (value) => {
// Perform async validation
const isValid = await validateId(value);
if (!isValid) {
return false;
}
return value;
}),
});
Code language: JavaScript (javascript)
In this example, we’ve defined a schema with an id
property that uses async validation. The refine()
method takes a callback function that can optionally performs async validation.
If the validation fails, the callback function should return a falsy value.
You’re right, I apologize for the confusion. Here’s a revised blog post that uses the correct syntax for safeParse()
and safeParseAsync()
methods:
Safely Parse Data
Zod is a powerful TypeScript-first validation library that makes it easy to define complex data schemas and validate them with ease. But what if you want to parse data safely without throwing an error? That’s where Zod’s safeParse()
and safeParseAsync()
methods come in.
What is safeParse()?
safeParse()
is a method in Zod that allows you to parse data safely without throwing an error. Instead of throwing an error when the data is invalid, safeParse()
returns a ZodParsedType<T>
object that contains both the parsed data and a boolean success
property that indicates whether the parsing was successful.
Here’s an example of how to use safeParse()
:
const schema = z.object({
name: z.string(),
age: z.number(),
});
const data = {
name: 'John',
age: '30', // age should be a number, but it's a string here
};
const parsedData = schema.safeParse(data);
if (parsedData.success) {
console.log(parsedData.data); // { name: 'John', age: 30 }
} else {
console.log('Data is invalid'); // This will be executed because age is not a number
}
Code language: JavaScript (javascript)
In this example, we’re using schema.safeParse()
to parse the data
object against the schema
we defined. The age
property is a string instead of a number, which should cause the schema.parse()
method to throw an error. However, since we’re using safeParse()
, it returns a ZodParsedType<T>
object that contains a success
property set to false
.
What is safeParseAsync()?
safeParseAsync()
is similar to safeParse()
, but it’s designed for parsing data asynchronously. This is useful when you need to parse data that requires async operations such as network requests.
Here’s an example of how to use safeParseAsync()
:
const schema = z.object({
name: z.string(),
age: z.number(),
});
async function getData() {
const data = await fetchData(); // Assume this fetches data asynchronously
const parsedData = await schema.safeParseAsync(data);
if (parsedData.success) {
console.log(parsedData.data); // { name: 'John', age: 30 }
} else {
console.log('Data is invalid');
}
}
Code language: JavaScript (javascript)
In this example, we’re using schema.safeParseAsync()
to parse the data fetched from an API endpoint. Since the data is fetched asynchronously, we need to use await
to wait for the data and parsed data to be available.
When to Use safeParse() and safeParseAsync()?
safeParse()
and safeParseAsync()
are useful when you need to parse data safely without throwing an error. This can be useful when handling user input or data from external sources that may be invalid.
It’s important to note that safeParse()
and safeParseAsync()
should not be used as a replacement for proper error handling. Instead, they should be used in conjunction with error handling to ensure that your code handles invalid data gracefully.
Conclusion – You are Now a Superhero for Data Validation
With Zod, you now have the power to become a superhero for data validation. You can define complex data schemas with ease, validate data against those schemas, customize error messages, handle nested objects, and even perform async validation. So go forth, my friend, and save the world (of data validation) with Zod! Remember, the power is in your hands.
Sharing is caring
Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: