2023-01-01 23:03:44 +08:00
# Zod validator middleware for Hono
2025-03-19 16:53:11 +08:00
[](https://codecov.io/github/honojs/middleware)
2025-05-27 16:47:54 +08:00
The validator middleware using [Zod ](https://zod.dev ) for [Hono ](https://honojs.dev ) applications. You can write a schema with Zod and validate the incoming values.
2023-01-01 23:03:44 +08:00
## Usage
```ts
import { z } from 'zod'
2023-02-24 17:22:02 +08:00
import { zValidator } from '@hono/zod-validator'
2023-01-01 23:03:44 +08:00
const schema = z.object({
name: z.string(),
age: z.number(),
})
app.post('/author', zValidator('json', schema), (c) => {
2023-02-24 17:22:02 +08:00
const data = c.req.valid('json')
2023-01-01 23:03:44 +08:00
return c.json({
success: true,
message: `${data.name} is ${data.age}` ,
})
})
```
2023-02-14 05:37:46 +08:00
Hook:
```ts
app.post(
'/post',
zValidator('json', schema, (result, c) => {
if (!result.success) {
return c.text('Invalid!', 400)
}
})
//...
)
```
2024-12-25 09:32:07 +08:00
Throw Error:
throw a zod validate error instead of directly returning an error response.
```ts
// file: validator-wrapper.ts
2025-03-19 16:53:11 +08:00
import { ZodSchema } from 'zod'
import type { ValidationTargets } from 'hono'
import { zValidator as zv } from '@hono/zod-validator'
export const zValidator = < T extends ZodSchema , Target extends keyof ValidationTargets > (
2025-01-05 17:04:45 +08:00
target: Target,
schema: T
) =>
zv(target, schema, (result, c) => {
if (!result.success) {
2025-03-19 16:53:11 +08:00
throw new HTTPException(400, { cause: result.error })
2025-01-05 17:04:45 +08:00
}
2025-03-19 16:53:11 +08:00
})
2024-12-25 09:32:07 +08:00
// usage
import { zValidator } from './validator-wrapper'
app.post(
'/post',
zValidator('json', schema)
//...
)
```
2025-04-27 19:12:13 +08:00
### Custom validation function
By default, this Validator validates values using `.safeParseAsync` .
```ts
await schema.safeParseAsync(value)
```
But, if you want to use the [`.passthrough` ](https://zod.dev/?id=passthrough ), you can specify your own function in `validationFunction` .
```ts
app.post(
'/',
zValidator('json', schema, undefined, {
validationFunction: async (schema, value) => {
return await schema.passthrough().safeParseAsync(value)
},
}),
(c) => {
// ...
}
)
```
2023-01-01 23:03:44 +08:00
## Author
Yusuke Wada < https: / / github . com / yusukebe >
## License
MIT