Overview
Validate request bodies, queries, and params with clear error messages.
Features
- JSON body validation
- Query parameter validation
- URL param validation
- Custom error formatting
Installation
npx hanma add hono-zod --framework hono
Dependencies
hono, @hono/zod-validator, zod
Code
import { z } from "zod";
import { zValidator } from "@hono/zod-validator";
import type { Context } from "hono";
/**
* Generic error formatter for Zod validation failures
*/
export const formatZodError = (result: any, c: Context) => {
if (!result.success) {
return c.json(
{
success: false,
message: "Validation failed",
errors: result.error.flatten().fieldErrors,
},
400
);
}
};
/**
* Example: JSON Body Validation
*/
export const createUserSchema = z.object({
name: z.string().min(2),
email: z.string().email(),
password: z.string().min(8),
});
export const validateCreateUser = zValidator("json", createUserSchema, formatZodError);
/**
* Example: Query Parameter Validation
*/
export const paginationSchema = z.object({
page: z.string().optional().transform(Number).default("1"),
limit: z.string().optional().transform(Number).default("10"),
});
export const validatePagination = zValidator("query", paginationSchema, formatZodError);
/**
* Example: URL Parameter Validation
*/
export const idParamSchema = z.object({
id: z.string().uuid("Invalid ID format"),
});
export const validateIdParam = zValidator("param", idParamSchema, formatZodError);
Usage
import { validateCreateUser, validatePagination } from './middleware/validator';
app.post('/users', validateCreateUser, handler);
Dependencies
hono@hono/zod-validatorzod
Frequently Asked Questions
How do I install Zod Validation?
Run the following command:
npx hanma add hono-zod --framework honoWhat dependencies are required?
This snippet requires: hono, @hono/zod-validator, 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
src/middleware/validator.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.