2024-11-08 11:08:18 +08:00
# Class-validator middleware for Hono
2025-03-19 16:53:11 +08:00
[](https://codecov.io/github/honojs/middleware)
2024-11-08 11:08:18 +08:00
The validator middleware using [class-validator ](https://github.com/typestack/class-validator ) for [Hono ](https://github.com/honojs/hono ) applications.
## Usage
```ts
import { classValidator } from '@hono/class-validator'
import { IsInt, IsString } from 'class-validator'
2025-03-19 16:53:11 +08:00
2024-11-08 11:08:18 +08:00
class CreateUserDto {
@IsString ()
2025-03-19 16:53:11 +08:00
name!: string
2024-11-08 11:08:18 +08:00
@IsInt ()
2025-03-19 16:53:11 +08:00
age!: number
2024-11-08 11:08:18 +08:00
}
2025-03-19 16:53:11 +08:00
2024-11-08 11:08:18 +08:00
const route = app.post('/user', classValidator('json', CreateUserDto), (c) => {
const user = c.req.valid('json')
return c.json({ success: true, message: `${user.name} is ${user.age}` })
})
```
With hook:
```ts
import { classValidator } from '@hono/class-validator'
import { IsInt, IsString } from 'class-validator'
class CreateUserDto {
@IsString ()
2025-03-19 16:53:11 +08:00
name!: string
2024-11-08 11:08:18 +08:00
2025-03-19 16:53:11 +08:00
@IsInt ()
age!: number
2024-11-08 11:08:18 +08:00
}
app.post(
2025-03-19 16:53:11 +08:00
'/user',
classValidator('json', CreateUserDto, (result, c) => {
2024-11-08 11:08:18 +08:00
if (!result.success) {
return c.text('Invalid!', 400)
2025-03-19 16:53:11 +08:00
}
2024-11-08 11:08:18 +08:00
})
//...
)
```
## Author
**Pr0m3ht3us** - https://github.com/pr0m3th3usex
## License
2025-03-19 16:53:11 +08:00
MIT