Lesson 13 / 23
Basic Input Validation
Reject bad payloads before they reach your logic.
Never trust the client
Check required fields, types, and ranges on the server — client-side checks can always be bypassed.
Manual validation
For serious apps, use a library like zod or express-validator — but the core idea is: validate, then respond 400 on failure.
app.post('/items', express.json(), (req, res) => {
const { name, price } = req.body;
if (typeof name !== 'string' || name.trim() === '') {
return res.status(400).json({ error: 'name is required' });
}
if (typeof price !== 'number' || price < 0) {
return res.status(400).json({ error: 'price must be a positive number' });
}
res.status(201).json({ name, price });
});Quick check: Which status code fits a request rejected for bad input?
- 500
- 400
- 200
Answer
400 — 400 Bad Request signals the client sent an invalid payload; 500 implies a server-side failure instead.