Data validation is a crucial aspect of any application, ensuring that the data inputted meets certain criteria or constraints. In Node.js, there are several libraries available for data validation, each with its own strengths and features. One such library is Zod, which provides a schema-based approach to data validation. In this tutorial you will learn how to implement data validation in Node.js using Zod.
What is Zod?
Zod is a TypeScript-first schema declaration and validation library. It allows developers to define data schemas using a concise and expressive syntax, enabling robust validation of data structures. While originally designed for TypeScript, Zod can also be used effectively in JavaScript projects.
Getting Started with Zod
Before diving into the implementation, you need to install Zod in your Node.js project. You can do this via npm or yarn:
npm install zod
Once installed, you can start defining your validation schemas using Zod’s API.
Defining Validation Schemas:
Zod schemas are defined using a chainable API that allows you to specify validation rules for each field in your data structure. Here’s a basic example:
const { z } = require('zod');
const userSchema = z.object({
username: z.string().min(3).max(30),
email: z.string().email(),
password: z.string().min(6),
age: z.number().int().min(18),
isAdmin: z.boolean()
});
In this schema:
username
is a string with a minimum length of 3 and a maximum length of 30 characters.email
is a valid email address.password
is a string with a minimum length of 6 characters.age
is an integer greater than or equal to 18.isAdmin
is a boolean value.
Validating Data:
Once you’ve defined your validation schema, you can use it to validate data objects. Zod provides a parse
method for this purpose:
const data = {
username: 'john_doe',
email: '[email protected]',
password: 'password123',
age: 25,
isAdmin: false
};
try {
const validatedData = userSchema.parse(data);
console.log('Validated Data:', validatedData);
} catch (error) {
console.error('Validation Error:', error.errors);
}
If the data object passes validation, parse
returns a new object with the validated data. Otherwise, it throws an error containing details about the validation failure.
The safeParse Method:
In Zod, the safeParse
function allows you to validate data without throwing an error if validation fails. Instead, it returns a result object indicating whether the validation succeeded or failed, along with the validated data or error details. This can be useful in scenarios where you want to handle validation errors gracefully without crashing your application. Let’s see how to use safeParse:
const { z } = require('zod');
const userSchema = z.object({
username: z.string().min(3).max(30),
email: z.string().email(),
password: z.string().min(6),
age: z.number().int().min(18),
isAdmin: z.boolean()
});
const data = {
username: 'john_doe',
email: '[email protected]',
password: 'password123',
age: 25,
isAdmin: false
};
const result = userSchema.safeParse(data);
if (result.success) {
console.log('Validation succeeded. Validated Data:', result.data);
} else {
console.error('Validation failed. Errors:', result.error.errors);
}
Using safeParse
allows you to handle validation results more gracefully, especially in situations where you want to provide feedback to the user or handle errors without crashing your application.
Zod with Express.js:
Using Zod for data validation in an Express.js application is straightforward. You can define validation middleware functions that validate incoming request data against Zod schemas before passing it to your route handlers. Or you can directly integrate Zod validation within the route handler in Express.js. Here’s how you can achieve that:
First, make sure to install the zod and express dependencies:
npm install express zod
const express = require('express');
const { z } = require('zod');
const app = express();
const port = 3000;
// Define Zod schema for user data
const userSchema = z.object({
username: z.string().min(3).max(30),
email: z.string().email(),
password: z.string().min(6),
age: z.number().int().min(18),
isAdmin: z.boolean()
});
// Route handler with validation
app.post('/user', (req, res) => {
const data = req.body;
const result = userSchema.safeParse(data);
if (result.success) {
// Valid data, process it
const validatedData = result.data;
// Here you can perform further operations with validatedData
res.json({ message: 'User created successfully', user: validatedData });
} else {
// Invalid data, send validation errors as response
res.status(400).json({ errors: result.error.errors });
}
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Zod in React Applications:
In React applications, you can use Zod for client-side data validation to ensure that the data entered by users meets certain criteria before submitting it to the server. You can integrate Zod validation within your React components to provide real-time feedback to users and prevent invalid data from being submitted. Here’s a basic example of how you can use Zod with React:
First install the zod in your react application:
npm install zod
Here is an example React component with Zod validation:
import { useState } from 'react';
import { z } from 'zod';
// Define Zod schema for user data
const userSchema = z.object({
username: z.string().min(3).max(30),
email: z.string().email(),
password: z.string().min(6),
age: z.number().int().min(18),
isAdmin: z.boolean()
});
function App() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
age: '',
isAdmin: false
});
const [errors, setErrors] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
const result = userSchema.safeParse(formData);
if (result.success) {
// Valid data, submit to server or perform further actions
console.log('Valid data:', result.data);
setErrors({});
} else {
// Invalid data, update errors state with validation errors
console.error('Validation errors:', result.error.errors);
setErrors(result.error.flatten());
}
};
return (
<div>
<h1>User Registration</h1>
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input type="text" name="username" value={formData.username} onChange={handleChange} />
{errors.username && <span>{errors.username}</span>}
</div>
<div>
<label>Email:</label>
<input type="email" name="email" value={formData.email} onChange={handleChange} />
{errors.email && <span>{errors.email}</span>}
</div>
<div>
<label>Password:</label>
<input type="password" name="password" value={formData.password} onChange={handleChange} />
{errors.password && <span>{errors.password}</span>}
</div>
<div>
<label>Age:</label>
<input type="number" name="age" value={formData.age} onChange={handleChange} />
{errors.age && <span>{errors.age}</span>}
</div>
<div>
<label>Is Admin:</label>
<input type="checkbox" name="isAdmin" checked={formData.isAdmin} onChange={handleChange} />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;
This is a very basic tutorial for how to use zod in your node.js or react.js app to implement data validations. To learn more about zod validations visit the official page of Zod Documentation.