Every API boundary is untrusted—validate shape, types, and business rules before persistence. Libraries like Zod, Joi, or express-validator reduce boilerplate.
Manual checks
function parseCreateUser(body) {
const email = String(body.email ?? '').trim();
if (!email.includes('@')) throw new Error('Invalid email');
const age = Number(body.age);
if (!Number.isInteger(age) || age < 0) throw new Error('Invalid age');
return { email, age };
}
Schema validation (Zod concept)
// npm install zod — locally
// const schema = z.object({ email: z.string().email(), age: z.number().int().min(0) });
Whitelist approach
Reject unknown fields in strict APIs—prevents mass-assignment vulnerabilities where clients set isAdmin: true.
Important interview questions and answers
- Q: Validate on client and server?
A: Client for UX; server is authoritative—never skip server validation. - Q: Sanitize vs validate?
A: Validate ensures data meets rules; sanitize transforms (trim, escape)—both may apply.
Self-check
- Why reject unknown JSON fields in strict APIs?
- What should happen when validation fails?
Pitfall: Client-side validation is UX only—always validate and sanitize on the server before trusting data.