Input validation
- Node.js course
- Advanced
- Lesson 22/83
- 5 min
Learn input validation with express-validator.
express-validator
express-validator is a module that validates incoming data in Express routes. It checks the request body, query, and params; bad data is caught before it is processed.
Basic usage: you validate the email field with body("email").isEmail(). You collect errors with validationResult(req) and return a 400 response if there are any. This pattern enforces the principle of never trusting user input.
body and validationResult
express-validator offers two core APIs. body("field") starts a validation chain; you add checks with methods like .isEmail(), .notEmpty(), .isLength({ min: 3 }).
You add the chain as middleware on the route. In the handler you call validationResult(req) and check .isEmpty(). If there are errors you get them with .array() and return them to the client.
Practice Log the type of body
Import body from express-validator. Log typeof body.
Starter code
// import the module, get body
// log its typeSample solution
const { body } = require("express-validator");
console.log(typeof body);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does express-validator do?
- Connects a database
- Validates input Correct answer
- Measures network speed
- Dosya okur
Explanation: express-validator does input validation.
2 Match each piece to its role
| Term | Meaning |
|---|---|
body("email") |
Email field |
validationResult |
Collects errors |
isEmail() |
Validates email |
notEmpty() |
Not empty |
3 Complete the module name
const { body } = require("____")
const { body } = require("express-validator")
Explanation: The express-validator module loads as 'express-validator'.