Node.js Express Form Validation
Validate form data in Node.js Express using express-validator middleware chains, custom sanitizers, grouped error responses, and conditional validation.
Code
import { body, validationResult } from 'express-validator';
export const validateLogin = [
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }).withMessage('Min 8 chars'),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
},
];What to watch for
- External dependency:
express-validator— install it before running the snippet.
Using it
Signature: export const validateLogin =
Import validateLogin and call it from your own module — the snippet is a drop-in helper, not an executable program.
The crux of the implementation is this line:
body('password').isLength({ min: 8 }).withMessage('Min 8 chars'),
One more line that carries real weight:
import { body, validationResult } from 'express-validator';
And the line that closes the loop:
return res.status(400).json({ errors: errors.array() });
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does this require external packages?
- Yes — `express-validator`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.