Input Validation
Overview
Never trust the client. If your React frontend has a form that restricts ages to '18+', a hacker can easily bypass React entirely by sending a raw HTTP request via Postman with age: -50. If you inject that raw data into your database, your system is corrupted. Input Validation is the architectural firewall in the backend that strictly mathematically validates every single incoming JSON payload before it touches your business logic.
Syntax
// Using 'Joi', the industry-standard validation library for Node.js
const Joi = require('joi');
// 1. Define a strict mathematical Schema
const userSchema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
age: Joi.number().integer().min(18).max(120), // Hackers cannot bypass this!
email: Joi.string().email({ minDomainSegments: 2 })
});
app.post('/api/register', (req, res) => {
// 2. Validate the incoming req.body against the Schema
const { error, value } = userSchema.validate(req.body);
if (error) {
// Intercept and throw a 400 Bad Request instantly!
return res.status(400).json({ error: error.details[0].message });
}
// If we reach here, 'value' is mathematically guaranteed to be clean!
res.status(201).json({ success: true, cleanData: value });
});Common Pitfalls
- Writing manual
if/elsevalidation chains. If you writeif (typeof req.body.age !== 'number'), you will end up writing hundreds of lines of fragile spaghetti code for every endpoint. Always use a declarative schema library like Joi, Zod, or Yup. - Validating after database processing. If you try to insert data, and rely on the Database's SQL constraints (like
VARCHAR(50)) to throw the error, you are wasting expensive Database I/O. Validation must happen at the absolute edge of the API (in a middleware) before the database is ever touched.
Interview Questions
Frontend validation is a purely cosmetic UX feature; it exists only to give fast visual feedback to the user. Because the frontend runs on the user's computer, a malicious actor can easily bypass it, modify the JavaScript, or use tools like cURL/Postman to send raw malicious payloads directly to your API endpoint.
Real-World Example
Abstracting Joi validation into a clean, reusable Express Middleware function.
// The Middleware Generator
const validateSchema = (schema) => (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.details[0].message });
next(); // It's clean, move to the controller!
};
// Applying it directly to the route pipeline!
app.post('/api/register', validateSchema(userSchema), (req, res) => {
// The controller is now beautifully small and safe.
db.insert(req.body);
});Check Your Knowledge
Test your understanding of Input Validation with these quick questions.