Zod is a
Zod provides runtime schema validation for typescript. Schema validation confirms that data adheres to a standard defined by the developer. It is advantageous when getting user data in forms, sending data to APIs, and more. Typically, typescript provides schema validation at the compile time only, whereas Zod provides validation at runtime.
To start with Zod, ensure node
and npm
are installed on your machine. We can use npm
to install Zod using the command given below:
npm install zod
Now, we’ll define a very simple schema validator. First, we import zod
in our file. Next, we define a simple string schema that accepts a string of minimum length 5 and maximum length 10. Now, if we parse a string of length 9, it will be parsed successfully and returned. Run the code below to see the output:
import { z } from "zod"const userInput = z.string().min(5).max(10);console.log(userInput.parse("Hello Zod"));
However, if the length of the string is more than 10 or less than 5, an error will be thrown. In the code given below, the length of the string is 24. Run the code to see the output.
import { z } from "zod"const userInput = z.string().min(5).max(10);console.log(userInput.parse("Hello Zod and Typescript"));
The output of the code snippet above throws a ZodError
. This error interrupts the runtime, which is undesirable in client-server web applications. However, we can avoid this error in Zod as discussed in the next section.
To avoid errors when parsing fails, we can use the safeParse
function. It returns status 400
and an object with the success
property set to true if the string is parsed successfully, otherwise, it’s set to false. In the latter case, the function also returns an error
property containing the error object.
In the code given below, we will use the safeParse
function. Run the code to see the output.
import { z } from "zod"const userInput = z.string().min(5).max(10);const result = userInput.safeParse("Hello Zod and Typescript");if (result.success) {console.log('Valid Data', result.data);} else {console.error('Invalid Data', result.error.message);}
The code will print Valid Data
along the data if the string is parsed successfully, otherwise it will print Invalid Data
along with the message
in the error
.
Similarly, we can use Zod to validate a complex object.
import { z } from 'zod'import { ZodTypeAny } from 'zod';const FormData = z.object({username: z.string().min(1).max(18),email: z.string().email(),});const validUserData = { username: 'Alice', email: 'alice@gmail.com' };const invalidUserData = { username: 'Bob', email: 'bobmail.com' };const validateFormData = (data: any, schema: ZodTypeAny) => {const result = schema.safeParse(data);if (result.success){console.log('Valid Data', result.data);} else {console.error('Invalid Data', result.error.message);}};console.log('Parsing valid user data');validateFormData(validUserData, FormData);console.log('Parsing invalid user data');validateFormData(invalidUserData, FormData);
The code implements the following steps:
Lines 4–7: We define an object called FormData
that contains two variables, username
and email
. This object defines our schema for a user.
Lines 9–10: We define sample data in variables validUserData
and invalidUserData
. Note the email
in invalidUserData
is bobmail.com
which is an invalid format.
Lines 12–19: We define a validateFormData
function. In this function, we have set the schema type to ZodTypeAny
so that it accepts any type of structure or data without prior validation. In the function, the result
variable stores the object returned by safeParse
function. If the data is parsed successfully, it prints Valid Data
along with data object. Otherwise, it prints the error message.
Lines 22–25: We call the validateFormData
function to validate validUserData
and invalidUserData
against FormData
.
Summing it up, Zod is a great way to ensure data validity and integrity in typescript applications. In this answer, we have discussed basic functions to parse and validate data. However, Zod offers a variety of functions to customize validation functions, transform data during validation, asynchronous validation, and more.
Free Resources