Input Validation (Node.js)
Input validation in Node.js checks that request data is present and correctly shaped before you use it. Libraries like Zod, Joi, and express-validator define schemas and reject bad input with clear errors.
Node.js
Never trust client input. Validation enforces rules — required fields, types, formats like email, value ranges — on the server, returning a 400 with helpful messages when data is invalid, so bad or malicious payloads never reach your database or business logic.
Schema libraries make this declarative. Zod (TypeScript-friendly) and Joi define a schema object and parse the input against it, throwing or returning errors on mismatch; express-validator adds validation as middleware on routes. A typical pattern validates req.body at the top of a handler and responds 400 if it fails.
Validation also enables coercion (turning the string '5' from a query into a number) and sanitization (trimming, normalizing). Keep validation close to the boundary — in middleware or the start of the handler — so the rest of your code can assume clean, typed data.
Syntax
const result = schema.safeParse(req.body);Examples
JavaScript
const { z } = require("zod");
const UserSchema = z.object({
email: z.string().email(),
age: z.number().int().min(0),
});
app.post("/users", (req, res) => {
const r = UserSchema.safeParse(req.body);
if (!r.success) return res.status(400).json(r.error.issues);
res.status(201).json(r.data);
});