Use Zod in JS

Validating Data in JavaScript with Zod
Zod is a TypeScript-first schema declaration and validation library that also works great in JavaScript. It allows you to define schemas for your data, ensuring that the data you receive and work with is in the format you expect. This helps prevent errors and makes your code more robust.
Why Use Zod?
- Type Safety: Even in JavaScript, Zod helps you enforce data types at runtime.
- Clear Syntax: Zod's syntax is straightforward and easy to learn.
- Extensibility: You can define custom validation rules to fit your specific needs.
- Integration: Zod integrates well with popular frameworks and libraries.
Getting Started
First, you'll need to install Zod:
npm install zod
# or
yarn add zod
Basic Example
Here's a simple example of how to use Zod to validate a user object:
import { z } from 'zod';
// Define a schema for a user object
const userSchema = z.object({
name: z.string(),
age: z.number().min(0),
email: z.string().email(),
});
// Example user data
const userData = {
name: 'John Doe',
age: 30,
email: 'john.doe@example.com',
};
// Validate the data
try {
const validatedData = userSchema.parse(userData);
console.log('Valid user data:', validatedData);
} catch (error) {
console.error('Validation errors:', error.errors);
}
In this example, we define a schema (userSchema) that specifies the types and constraints for the name, age, and email properties. We then use userSchema.parse() to validate the userData object. If the data is valid, it returns the validated data. If not, it throws an error with details about the validation failures.
More Complex Example
Zod can handle more complex scenarios, such as arrays, objects, and custom validations:
import { z } from 'zod';
const productSchema = z.object({
id: z.string().uuid(),
name: z.string().min(3).max(100),
price: z.number().positive(),
tags: z.array(z.string()).optional(),
dimensions: z.object({
width: z.number(),
height: z.number(),
}),
// Custom validation for a product code
productCode: z.string().refine(
(code) => /^[A-Z]{3}-\d{3}$/.test(code),
{ message: 'Invalid product code format' }
),
});
const productData = {
id: 'a1b2c3d4-e5f6-4789-a0b1-c2d3e4f5a6b7',
name: 'Awesome Product',
price: 99.99,
tags: ['featured', 'new'],
dimensions: { width: 10, height: 5 },
productCode: 'ABC-123',
};
try {
const validatedProduct = productSchema.parse(productData);
console.log('Valid product data:', validatedProduct);
} catch (error) {
console.error('Validation errors:', error.errors);
}