2024-11-15 04:17:22 +08:00
|
|
|
# Ajv validator middleware for Hono
|
|
|
|
|
2025-03-19 16:53:11 +08:00
|
|
|
[](https://codecov.io/github/honojs/middleware)
|
|
|
|
|
2024-11-15 04:17:22 +08:00
|
|
|
Validator middleware using [Ajv](https://github.com/ajv-validator/ajv) for [Hono](https://honojs.dev) applications.
|
|
|
|
Define your schema with Ajv and validate incoming requests.
|
|
|
|
|
|
|
|
## Usage
|
|
|
|
|
|
|
|
No Hook:
|
|
|
|
|
|
|
|
```ts
|
2025-03-19 16:53:11 +08:00
|
|
|
import { type JSONSchemaType } from 'ajv'
|
|
|
|
import { ajvValidator } from '@hono/ajv-validator'
|
|
|
|
|
2024-11-15 04:17:22 +08:00
|
|
|
const schema: JSONSchemaType<{ name: string; age: number }> = {
|
|
|
|
type: 'object',
|
|
|
|
properties: {
|
|
|
|
name: { type: 'string' },
|
|
|
|
age: { type: 'number' },
|
|
|
|
},
|
|
|
|
required: ['name', 'age'],
|
|
|
|
additionalProperties: false,
|
2025-03-19 16:53:11 +08:00
|
|
|
} as const
|
2024-11-15 04:17:22 +08:00
|
|
|
|
|
|
|
const route = app.post('/user', ajvValidator('json', schema), (c) => {
|
2025-03-19 16:53:11 +08:00
|
|
|
const user = c.req.valid('json')
|
|
|
|
return c.json({ success: true, message: `${user.name} is ${user.age}` })
|
|
|
|
})
|
2024-11-15 04:17:22 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
Hook:
|
|
|
|
|
|
|
|
```ts
|
2025-03-19 16:53:11 +08:00
|
|
|
import { type JSONSchemaType } from 'ajv'
|
|
|
|
import { ajvValidator } from '@hono/ajv-validator'
|
2024-11-15 04:17:22 +08:00
|
|
|
|
|
|
|
const schema: JSONSchemaType<{ name: string; age: number }> = {
|
|
|
|
type: 'object',
|
|
|
|
properties: {
|
|
|
|
name: { type: 'string' },
|
|
|
|
age: { type: 'number' },
|
|
|
|
},
|
|
|
|
required: ['name', 'age'],
|
|
|
|
additionalProperties: false,
|
2025-03-19 16:53:11 +08:00
|
|
|
}
|
2024-11-15 04:17:22 +08:00
|
|
|
|
|
|
|
app.post(
|
|
|
|
'/user',
|
|
|
|
ajvValidator('json', schema, (result, c) => {
|
|
|
|
if (!result.success) {
|
2025-03-19 16:53:11 +08:00
|
|
|
return c.text('Invalid!', 400)
|
2024-11-15 04:17:22 +08:00
|
|
|
}
|
|
|
|
})
|
|
|
|
//...
|
2025-03-19 16:53:11 +08:00
|
|
|
)
|
2024-11-15 04:17:22 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
## Author
|
|
|
|
|
|
|
|
Illia Khvost <https://github.com/ikhvost>
|
|
|
|
|
|
|
|
## License
|
|
|
|
|
|
|
|
MIT
|