Express.js Masterclass
The Professional Backend Framework01.Home02.Introduction03.Express vs Native Node04.Express Generator05.Request Object (req)06.Response Object (res)07.Advanced Routing08.URL Params & Query09.Body Parsing10.Template Engines (EJS)11.Serving Static Files12.Middleware Architecture13.Must-Have Middleware14.File Uploads (Multer)15.Custom Error Handling16.Cookies & Sessions17.User Auth (Passport)18.Database Integration19.Data Validation20.Socket.io in Express21.Security & Helmet
Data Validation
Never trust user input. Validating data on the server side is the first line of defense against bugs and security vulnerabilities.
1. Using express-validator
It's a set of middleware that wraps validator.js functions.
const { body, validationResult } = require('express-validator');
app.post('/register', [
body('email').isEmail().withMessage('Enter a valid email'),
body('password').isLength({ min: 5 }).withMessage('Too short')
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Valid data!');
});2. Data Sanitization
Sanitizing ensures that the data is in the format you expect (e.g., trimming whitespace or converting to lower case).
body('email').isEmail().normalizeEmail().trim()3. Schema-based Validation (Joi)
For complex objects, Joi is a powerful alternative.
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
});Best Practice: Perform Client-side validation for user experience and Server-side validation for security. Client-side validation can easily be bypassed.