Input validation checks that data entering your system has the expected type, format, length and range before you use it, rejecting anything else. It's important for security because many attacks (injection, XSS, path traversal, prototype pollution, denial of service via huge payloads) start with unexpected input. Rules: validate on the server (client-side validation is only UX), prefer allowlists over blocklists, validate at every trust boundary with a schema, and pair validation with context-specific output encoding and parameterized queries, because valid data can still be dangerous in the wrong context.
// client: instant feedback, can be bypassed with DevTools, curl or a script
<input type="email" required maxLength={254} />
// server: the actual security control
app.post('/api/profile', (req, res) => {
const result = ProfileSchema.safeParse(req.body);
if (!result.success) return res.status(400).json({ errors: result.error.flatten() });
saveProfile(req.user.id, result.data); // only validated, typed data goes further
});
Anything that reaches your API can be crafted by an attacker; front-end checks never count as a defence.
import { z } from 'zod';
const ProfileSchema = z.object({
displayName: z.string().trim().min(1).max(50),
website: z.string().url().max(200).refine((u) => /^https?:/i.test(u), 'Must be http(s)').optional(),
age: z.number().int().min(13).max(130),
role: z.enum(['viewer', 'editor']), // allowlist; never accept "admin" from the client
}).strict(); // reject unknown keys (mass-assignment protection)
{ "$ne": null }).express.json({ limit: '100kb' })).isAdmin or price (mass assignment).The same schema can run in the browser for UX and on the server for enforcement, and TypeScript types can be inferred from it.
// blocklist: always incomplete
if (filename.includes('../')) reject(); // bypass: '..%2f', '..\\', unicode tricks
// allowlist: define what's allowed
const SAFE_NAME = /^[a-z0-9_-]{1,64}\.(png|jpe?g|webp)$/i;
if (!SAFE_NAME.test(filename)) reject();
For file paths, also resolve and check that the final path stays inside the intended directory.
Valid input can still be harmful when used in a different context:
O'Brien breaks string-built SQL; use parameterized queries.<b> is fine as text but dangerous in innerHTML; encode on output or sanitize HTML.javascript:… unless you check the protocol.So validation reduces attack surface; encoding and safe APIs at the point of use prevent injection.
Content-Type), re-encode images, store outside the web root, scan if needed.postMessage data and third-party API responses: validate shape before trusting them.__proto__, constructor and prototype keys or use Object.create(null)/Map, to prevent prototype pollution.400/422 and field-level messages; don't try to "fix" malicious input silently.Spotted a mistake or a rights concern? Report an issue