DEV Community

Cover image for Easily Validate Your Node.js Inputs with Zod
Beπ ✨
Beπ ✨

Posted on • Updated on • Originally published at benoitpetit.dev

Easily Validate Your Node.js Inputs with Zod

Substack Newsletter

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.


🫶 If you appreciate my posts and would like to support my work, feel free to make a donation by clicking on the Stripe Sponsor link below or by scanning the QR code. Stripe Link Sponsor


Stripe Sponsor


👀 See me here :

Latest comments (1)

Collapse
 
awebcode profile image
Md-Asikur

great🚀✌