Overview
Validate request body, params, and query with Zod. Type-safe validation.
Features
- Body validation
- Query and params validation
- Type inference
- Custom error messages
Installation
npx hanma add validation-zod
Dependencies
zod
Code
import { Request, Response, NextFunction } from 'express';
import { AnyZodObject, ZodError } from 'zod';
export const validate = (schema: AnyZodObject) => async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
await schema.parseAsync({
body: req.body,
query: req.query,
params: req.params,
});
return next();
} catch (error) {
if (error instanceof ZodError) {
return res.status(400).json({
success: false,
message: 'Validation failed',
errors: error.errors,
});
}
return res.status(500).json({ success: false, message: 'Internal server error' });
}
};
Usage
import { validate } from './middleware/validation-zod';
import { z } from 'zod';
const schema = z.object({ email: z.string().email() });
app.post('/user', validate(schema), handler);
Dependencies
zod
Frequently Asked Questions
How do I install Zod Validation?
Run the following command:
npx hanma add validation-zodWhat dependencies are required?
This snippet requires: zod. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
middleware/validation-zod.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.