Validation Middleware
Validate the request body, route params and query with validate() from @axiljs/validation: coerced, typed data on success and a 422 error with field details.
On this page8
validate() checks the body, route params and query string of a request against schemas built with v before your handler runs. Valid requests reach the handler with clean data: strings coerced to numbers and booleans, defaults filled in, transforms applied. Invalid requests never reach it; they get a 422 with every problem listed.
1import { Application } from '@axiljs/core'
2import { v, validate } from '@axiljs/validation'
3
4const app = new Application()
5
6const createUser = v.object({
7 name: v.string().trim().min(2).max(100),
8 email: v.string().email(),
9 role: v.enum(['admin', 'user']).default('user')
10}).strip()
11
12app.post('/users', validate({ body: createUser }), (req, res) => {
13 res.created(req.body) // { name, email, role }, trimmed, defaulted, unknown keys removed
14})validate(options)
| Option | Type | Validates |
|---|---|---|
body | BaseValidator | req.body |
params | BaseValidator | req.params (route parameters such as :id) |
query | BaseValidator | req.query |
Any schema works, but an object schema from v.object() is the usual choice. Omit a source to leave it unchecked.
Each source is parsed with the schema's parse():
- On success the parsed data replaces
req.body,req.paramsorreq.query. That includes coercion,.default()values,.trim(),.transform()results and.strip(). - On failure the errors are collected. All three sources are always checked, so one response reports every problem in the body, params and query together.
If anything failed, the middleware calls next() with a ValidationError (HTTP 422, code VALIDATION_ERROR, message Request validation failed). Its details is the array of field errors.
Field errors
| Field | Type | Description |
|---|---|---|
path | string | Field path: email, address.street, tags[0]. root when the whole value failed, e.g. the body is not an object |
message | string | Readable message, e.g. email must be a valid email address |
code | string | Machine-readable code (table below) |
source | 'body' | 'params' | 'query' | Which part of the request failed |
| Code | Raised by |
|---|---|
REQUIRED | A missing field without .optional() or .default() |
NULL_VALUE | null on a field without .nullable() |
TYPE_ERROR | Wrong type, e.g. must be a number |
MIN_LENGTH / MAX_LENGTH | String length limits |
MIN_VALUE / MAX_VALUE / INTEGER / POSITIVE | Number rules |
EMAIL / URL / PATTERN | String formats |
MIN_ITEMS / MAX_ITEMS | Array length limits |
ENUM / LITERAL / UNION | A value outside v.enum(), v.literal() or v.union() |
CUSTOM | A .custom() rule |
TRANSFORM_ERROR | A .transform() function that threw (reported with path root) |
See Schema validation for every validator and its rules.
Returning the errors to the client
The default error handler sends { error: { code, message } } (plus stack outside production). It does not include details, so out of the box the client sees Request validation failed without the field list. Add an error handler that does:
1import { ValidationError } from '@axiljs/core'
2
3app.use((err, _req, res, next) => {
4 if (err instanceof ValidationError) {
5 return res.status(422).json({
6 error: { code: err.code, message: err.message, details: err.details }
7 })
8 }
9 next(err)
10})1{
2 "error": {
3 "code": "VALIDATION_ERROR",
4 "message": "Request validation failed",
5 "details": [
6 { "path": "email", "message": "email must be a valid email address", "code": "EMAIL", "source": "body" },
7 { "path": "page", "message": "page must be a number", "code": "TYPE_ERROR", "source": "query" }
8 ]
9 }
10}Note
Import the error class from @axiljs/core (or @axiljs/common). @axiljs/validation also exports a type called ValidationError, which describes one field error, and it cannot be used with instanceof.
Query strings and route params
Query and route values always arrive as strings. v.number() and v.boolean() coerce them, so after validation they are real numbers and booleans:
| Validator | Accepted strings | Result |
|---|---|---|
v.number() | Any non-empty string that is a finite number ('2', '-1.5', '1e3') | number |
v.boolean() | 'true', '1' / 'false', '0' | boolean |
1app.get('/users',
2 validate({
3 query: v.object({
4 page: v.number().integer().min(1).default(1),
5 limit: v.number().integer().max(100).default(20),
6 active: v.boolean().optional()
7 })
8 }),
9 (req, res) => {
10 const { page, limit, active } = req.query as unknown as { page: number; limit: number; active?: boolean }
11 // GET /users?page=2&active=true → page === 2, limit === 20, active === true
12 res.success({ page, limit, active })
13 }
14)
15
16app.get('/users/:id',
17 validate({ params: v.object({ id: v.number().integer().positive() }) }),
18 (req, res) => res.success({ id: req.params.id }) // a number at runtime
19)An empty value such as ?page= is the empty string, not a missing field, so .default() does not apply and it fails with page must be a number. Leave the parameter out to get the default.
Typing the validated data
req.body, req.params and req.query keep their framework types after validation. Infer the type from the schema and cast once:
1import { v, validate, type InferValidator } from '@axiljs/validation'
2
3const createOrder = v.object({
4 sku: v.string(),
5 qty: v.number().integer().positive()
6})
7type CreateOrder = InferValidator<typeof createOrder>
8
9app.post('/orders', validate({ body: createOrder }), (req, res) => {
10 const order = req.body as CreateOrder
11 res.created(order)
12})Unknown fields
Object schemas keep keys they do not declare. Call .strip() to drop them, which stops clients from setting fields such as isAdmin or id that you pass straight to the database:
validate({ body: v.object({ name: v.string() }).strip() })
// { name: 'Ada', isAdmin: true } → { name: 'Ada' }Validating without middleware
For data that does not come from a request (queue messages, webhooks, config), call parse() on the schema directly:
1const result = createOrder.parse(message)
2if (!result.success) {
3 log.warn('bad message', { errors: result.errors })
4 return
5}
6await orders.create(result.data!)Related
Was this page helpful?