Input validation and sanitization help keep your app safe and working right by checking and cleaning user data before using it.
Input validation and sanitization in Node.js
import { body, validationResult } from 'express-validator'; app.post('/submit', [ body('email').isEmail().normalizeEmail(), body('age').isInt({ min: 0 }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // Use sanitized and validated data here res.send('Data is valid and safe!'); });
Use express-validator middleware to validate and sanitize inputs in Node.js apps.
Always check validationResult to handle errors before using data.
body('username').trim().escape()body('email').isEmail().normalizeEmail()body('age').isInt({ min: 0, max: 120 })
This Node.js app uses Express and express-validator to check and clean user input for username, email, and age. If input is bad, it sends errors. If good, it welcomes the user with their cleaned data.
import express from 'express'; import { body, validationResult } from 'express-validator'; const app = express(); app.use(express.json()); app.post('/register', [ body('username').trim().escape(), body('email').isEmail().normalizeEmail(), body('age').isInt({ min: 0, max: 120 }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } res.send(`Welcome, ${req.body.username}! Your email is ${req.body.email} and age is ${req.body.age}.`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always validate and sanitize inputs to avoid security risks like injection attacks.
Use libraries like express-validator to simplify input checks.
Test your validation by sending different inputs using tools like Postman or browser DevTools.
Input validation checks if data is correct and safe.
Sanitization cleans data to remove harmful parts.
Use middleware like express-validator in Node.js for easy validation and sanitization.