🚀 Express.js Intermediate

What is input validation and how do you do it in Express?

Answer

Input validation ensures data received from users meets your requirements before processing it. Never trust user input — validate at the API boundary. The two most popular approaches: express-validator (integrates tightly with Express): define validation chains like body('email').isEmail().normalizeEmail() in route handlers, then check validationResult(req). Zod or Joi: define a schema and validate req.body against it. These work in middleware that can be reused. Validation should check type, format, length, range, and allowed values. Respond with 400 and detailed error messages when validation fails. Sanitize inputs (strip HTML, trim whitespace) to prevent injection attacks.