DEV Community

Cover image for Easily Validate Your Node.js Inputs with Zod
ben.
ben.

Posted on

 

Easily Validate Your Node.js Inputs with Zod

In this tutorial, we will explore how to use Zod, a TypeScript-first schema validation library, to validate inputs in our Node.js application. Zod uses static type inference to automatically generate validators from our TypeScript types, eliminating the need to manually write validation rules.

To start, we will install Zod using npm:

npm install zod
Enter fullscreen mode Exit fullscreen mode

Example Usage

In this example, we will validate an object containing information about a user. We will define a TypeScript type for this object and use Zod to generate a validator from this type.

import * as z from 'zod'

interface User {
  name: string;
  age: number;
  email: string;
}

const userSchema = z.object({
  name: z.string().nonempty(),
  age: z.number().positive(),
  email: z.string().email()
});
Enter fullscreen mode Exit fullscreen mode

Here, we have defined our user schema using Zod's string, number, and email validation methods. We can now use this validator to validate user objects:

const validUser = { name: 'John Doe', age: 30, email: 'johndoe@example.com' };
const valid = userSchema.validate(validUser);
console.log(valid); // { name: 'John Doe', age: 30, email: 'johndoe@example.com' }

const invalidUser = { name: '', age: -5, email: 'notanemail' };
const error = userSchema.validate(invalidUser);
console.log(error); // { name: 'string must not be empty', age: 'number must be positive', email: 'string must be a valid email' }
Enter fullscreen mode Exit fullscreen mode

Integration with Node.js

To integrate Zod with our Node.js application, we can use the validator generated by Zod in an Express middleware to validate inputs in our API.

import * as express from 'express';

const app = express();

app.use(express.json());

app.post('/users', (req, res) => {
  const { error, value } = userSchema.validate(req.body);

  if (error) {
    return res.status(400).send(error);
  }

  // Input is valid, we can continue processing the request
  // ...
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

By using Zod, we can easily validate inputs in our Node.js application using TypeScript's static type inference. This allows us to define our validation schemas alongside our data model, eliminating the need to manually write validation rules. Additionally, using Zod can also improve the readability and maintainability of our code, as validation errors are clearly defined in the schema. Overall, Zod is a useful tool for any Node.js developer using TypeScript to ensure inputs in their application conform to specific validation rules.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!