Don't worry too much, you can safely use Zod mode for data validation in Node projects

ffb5fa8a0d1ab46a6884a1e850660c66.jpeg

Data validation can be a daunting task, especially when dealing with data from different sources, whose structure and format are unknown. It's important to ensure that data coming from forms, APIs, or other third-party sources conforms to the schema we define in our application.

Data validation is essential in any application development as it ensures the accuracy and completeness of the data we receive.

Why data validation is important.

  • Prevent errors from occurring by ensuring that data entered into our applications is correct and in the correct format.

  • Improve the security of our systems by preventing malicious input that could compromise the security of our applications.

Facilitates data analysis by ensuring that the data we allow is accurate and reliable so that useful insights can be more easily generated.
However, data validation can be very challenging without the right tools.

What is Zod

Zod is a TypeScript-based schema declaration and validation library. I use the term "schema" to refer broadly to any data type, from simple strings to complex nested objects.

Zod allows you to declare any type of data schema and validate the data in a type-safe manner. Once you define a validator, Zod can automatically infer static TypeScript types. Unlike TypeScript, which performs type checking at compile time, Zod provides runtime type checking, giving us an extra layer of type safety.

Potential benefits of using Zod for data validation

  • Type safety. It enables you to define data in a more type-safe manner, which can result in more robust and reliable code.

  • easy to use. Zod's API uses chainable interfaces (such as z.string().min(20).nonempty()) to define and validate data schemas, which is simple and intuitive.

  • Customizability. Zod allows us to create custom error messages and other validation options such as data conversion and conditional validation.

  • Performance and Developer Experience (DX). With speed and efficiency at its core, Zod provides a friendly developer experience thanks to its simple and intuitive API.

Validate data with Zod

In this section, we'll explore how to use zod to define and validate various data types. The following example shows how we receive data from the frontend via the API and validate it against the zod data schema we define.

The following code shows an Express API that handles user login:

import { Request, Response, Router } from "express";
import { z } from "zod";

const router = Router();

const userSchema = z.object({
  email: z.string().email().nonempty(),
  password: z.string().min(8).nonempty(),
});

function signIn(req: Request, res: Response) {
  const { email, password } = req.body;

  try {
    // Validate the incoming data against the userSchema
    userSchema.parse({ email, password });
    // If validation passes, further validate against data in db
  } catch (error) {
    // If validation fails, handle the error
    res.status(400).json({
      error: error,
    });
  }
}

// Routes
router.post("/signin", signIn);

export default router;
  • In the above code, we defined a userSchema object using the zod library, which has email and password properties. Then, we add some validation rules like .string().email().nonempty() that we can use later to validate user-supplied data. Note that the .email() method only checks basic email formatting and will not flag errors for emails that contain printable characters, quoted local parts, or contain emoji.

  • With zod schemas, the .parse method validates the provided data against the defined schema. If validation is successful, zod will return a deep clone of the data with full type information. If validation fails, zod will throw an error.

  • We can use the .safeParse method on a schema when we want to handle validation errors gracefully without having Zod throw an error. The method returns an object with the success property set to a boolean value, the data property contains the parsed data (if validation succeeded), and the error property contains the validation error (if validation failed).

import { Request, Response, Router } from "express";
import { z } from "zod";

const router = Router();

const userSchema = z.object({
  email: z.string().email().nonempty(),
  password: z.string().min(8).nonempty(),
});

function signIn(req: Request, res: Response) {
  const { email, password } = req.body;

  // Validate the incoming data against the userSchema
  const result = userSchema.safeParse({ email, password });

  if (!result.success) {
    // If validation fails, handle the error
    res.status(400).json({
      error: result.error,
    });
    return;
  }

  // zod validation passed, further validate against data values in db

}

// Routes
router.post("/signin", signIn);

export default router;

If you need to perform asynchronous validation, you can use the .parseAsync and .safeParseAsync methods.

Zod functional architecture

Zod also allows you to define and validate the inputs passed from functions and the outputs returned. You can define function patterns in Zod as follows

z.function(args, returnType)

It takes two parameters, the first is the input parameter, and the second parameter is the function return type you expect to return from the function. The return type can be a data schema defined by zod.

const signInSchema = z.function(z.object({
  body: z.object({
    email: z.string().email().nonempty(),
    password: z.string().min(8).nonempty(),
  })
}), z.undefined());

// Usage example
const req = { body: { email: "[email protected]", password: "password" } };
const res = { status: (code: number) => ({ json: (data: any) => console.log(code, data) }) };

const result = signInSchema.safeParse(signIn);
if (result.success) {
  result.data(req, res);
} else {
  console.error(result.error);
}

Zod function mode has two parameters: input mode and output mode. In this case, the input schema is an object with a body property that has email and password fields. Since the function does not return anything, the output mode is undefined.

Using signInSchema, we can call signInSchema.safeParse(signIn) and check the success property of the result. If true, we can call request and response objects using the result's data property. If false, we can handle errors using the result's error property.

type coercion

Zod provides built-in coercion functionality during validation that automatically converts input data to the required data type. This is useful when you need to validate data from an external source and make sure it matches the expected format or data type.

Here's an example of using coercion in Zod:

const { z } = require("zod");

const schema = z.object({
  name: z.string(),
  age: z.number().optional().transform((value) => {
    if (typeof value === "string") {
      return parseInt(value, 10);
    }
    return value;
  }),
});

const input = { name: "John", age: "20" };
const validatedData = schema.parse(input);

console.log(validatedData);
// Output: { name: "John", age: 20 }

In this example, the age field is optional and defined as a number. We use the convert method to coerce the input value to a number if it was provided as a string. If the input value is already a number, the function will simply return it.

Note that while casting can be useful in some situations, it can also introduce unexpected behavior and potential bugs. You should use casting with caution and make sure it works for your use case.

Here are some potential reasons why you might prefer Zod over Joi and Yup:

  • Zod is a relatively new library (first released in 2020) that aims to provide a more modern and user-friendly approach to schema validation. It has a simple and intuitive API designed to be easy to use and understand.

  • Zod supports both synchronous and asynchronous validation, which can be useful in some cases, such as when you need to validate data retrieved from an API or database.

  • Zod takes type safety very seriously and provides built-in support for TypeScript types. This is especially helpful if your project is already using TypeScript.

  • Zod is very customizable and extensible, allowing you to define custom validation rules and error messages to suit your specific needs.

Finish

Data validation is an important part in any application development, it ensures the accuracy and completeness of the data we receive. However, data validation can be a challenging task without the right tools.

Zod provides a TypeScript-based schema declaration and validation library that allows us to define any type of data schema in a type-safe manner and validate the data.

Through its type safety, ease of use, customizability and developer experience, Zod can provide significant benefits in terms of data validation. By implementing validation with Zod in your application, you can make the data validation process more robust, reliable, and efficient.

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Fan benefits

Share a NodeJs background template source code based on Tailwind Css, if you want to learn nodejs and tailwindcss, don't miss this source code.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132613552