Validating Input
Never trust data from the client. A request body can be missing, have the wrong types, contain extra fields or hold values far too large. Validation checks the input at the edge of your app so the rest of your code can assume clean data.
What to check
| Check | Example |
|---|---|
| presence | title is required |
| type | price is a number, not "12" |
| format | email looks like an email, date is ISO 8601 |
| range / length | quantity 1–100, name ≤ 80 characters |
| allowed values | status is one of draft, published |
| unknown fields | reject or strip fields you don't expect |
Respond with 400 (or 422) and tell the client which fields are wrong, so they can fix all problems in one go.
A tiny schema validator
Libraries like Zod, Joi, Yup or express-validator do this for you. Writing a minimal version first shows exactly what they do:
type Rule = (value: unknown) => string | null;
const required: Rule = (v) => (v === undefined || v === null || v === '' ? 'is required' : null);
const isString: Rule = (v) => (v === undefined || typeof v === 'string' ? null : 'must be a string');
const isNumber: Rule = (v) => (v === undefined || (typeof v === 'number' && Number.isFinite(v)) ? null : 'must be a number');
const maxLen = (n: number): Rule => (v) => (typeof v === 'string' && v.length > n ? `must be at most ${n} characters` : null);
const min = (n: number): Rule => (v) => (typeof v === 'number' && v < n ? `must be >= ${n}` : null);
type Schema = Record<string, Rule[]>;
function validate(schema: Schema, input: Record<string, unknown>) {
const errors: Record<string, string> = {};
for (const [field, rules] of Object.entries(schema)) {
for (const rule of rules) {
const message = rule(input[field]);
if (message) { errors[field] = message; break; }
}
}
for (const key of Object.keys(input)) {
if (!(key in schema)) errors[key] = 'is not allowed';
}
return errors;
}
const productSchema: Schema = {
name: [required, isString, maxLen(20)],
price: [required, isNumber, min(0)],
};
console.log(validate(productSchema, { name: 'Desk lamp', price: 39.5 }));
console.log(validate(productSchema, { name: 'An extremely long product name', price: -1 }));
console.log(validate(productSchema, { price: '12', admin: true }));{}
{ name: 'must be at most 20 characters', price: 'must be >= 0' }
{
name: 'is required',
price: 'must be a number',
admin: 'is not allowed'
}
Validation as middleware
Wrap the validator in a middleware factory, so every route declares its schema next to its path:
const express = require('express');
const rules = {
required: (v) => (v === undefined || v === '' ? 'is required' : null),
string: (v) => (v === undefined || typeof v === 'string' ? null : 'must be a string'),
int: (v) => (v === undefined || Number.isInteger(v) ? null : 'must be an integer'),
oneOf: (...allowed) => (v) => (v === undefined || allowed.includes(v) ? null : `must be one of ${allowed.join(', ')}`),
};
function validateBody(schema) {
return (req, res, next) => {
const body = req.body ?? {};
const errors = {};
for (const [field, checks] of Object.entries(schema)) {
for (const check of checks) {
const msg = check(body[field]);
if (msg) { errors[field] = msg; break; }
}
}
if (Object.keys(errors).length) {
return res.status(422).json({ error: 'Validation failed', fields: errors });
}
// keep only the fields the schema knows about
req.body = Object.fromEntries(Object.keys(schema).filter((k) => k in body).map((k) => [k, body[k]]));
next();
};
}
const app = express();
app.use(express.json());
app.post('/tickets',
validateBody({
title: [rules.required, rules.string],
priority: [rules.required, rules.oneOf('low', 'normal', 'high')],
estimate: [rules.int],
}),
(req, res) => res.status(201).json({ created: req.body }),
);
const server = app.listen(0, async () => {
const url = `http://localhost:${server.address().port}/tickets`;
const send = async (body) => {
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
console.log(res.status, await res.text());
};
await send({ title: 'Fix login', priority: 'high', estimate: 3, sneaky: 'x' });
await send({ priority: 'urgent', estimate: 2.5 });
server.close();
});201 {"created":{"title":"Fix login","priority":"high","estimate":3}}
422 {"error":"Validation failed","fields":{"title":"is required","priority":"must be one of low, normal, high","estimate":"must be an integer"}}
Notice that the unknown sneaky field was stripped before the handler saw the body.
Validating params and query too
Bodies aren't the only input. req.params and req.query are strings (or arrays), so coerce them before checking:
const express = require('express');
const app = express();
app.get('/products', (req, res) => {
const errors = {};
const maxPrice = req.query.maxPrice === undefined ? undefined : Number(req.query.maxPrice);
if (maxPrice !== undefined && (Number.isNaN(maxPrice) || maxPrice < 0)) errors.maxPrice = 'must be a non-negative number';
const inStock = req.query.inStock;
if (inStock !== undefined && !['true', 'false'].includes(inStock)) errors.inStock = 'must be true or false';
if (Object.keys(errors).length) return res.status(400).json({ fields: errors });
res.json({ maxPrice: maxPrice ?? null, inStock: inStock === undefined ? null : inStock === 'true' });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}/products`;
for (const qs of ['?maxPrice=25&inStock=true', '?maxPrice=cheap&inStock=yes']) {
const res = await fetch(base + qs);
console.log(res.status, await res.text());
}
server.close();
});200 {"maxPrice":25,"inStock":true}
400 {"fields":{"maxPrice":"must be a non-negative number","inStock":"must be true or false"}}
Using a library: Zod
In production use a schema library. With Zod, one schema gives you validation and a TypeScript type:
import { z } from 'zod';
const Ticket = z.object({
title: z.string().min(1).max(120),
priority: z.enum(['low', 'normal', 'high']),
estimate: z.number().int().positive().optional(),
});
type Ticket = z.infer<typeof Ticket>;
app.post('/tickets', (req, res) => {
const result = Ticket.safeParse(req.body);
if (!result.success) return res.status(422).json({ error: result.error.issues });
const ticket: Ticket = result.data; // typed and stripped of unknown keys
// …
});Tip: Validation (is the shape right?) is different from business rules (is this email already registered?). Do the cheap shape checks in middleware, the database-backed rules in your service layer — and answer the latter with 409 Conflict.
Test yourself
Why should a validator report all invalid fields at once?
- It's faster for the server
- The client can fix every problem in one round-trip
- HTTP requires it
- It hides which fields failed
What is typeof req.query.limit for /items?limit=10?
- number
- string
- bigint
- undefined
Which status code fits a request whose JSON is well-formed but fails validation rules?
- 200
- 404
- 422
- 500