HuntExams Academy logo
Node.js ยท Chapter 24 of 43

Input Validation

Validation ensures incoming data meets expected rules (required fields, correct types, valid formats) before your app processes it. Never trust client input.

Libraries like `joi`, `zod`, or `express-validator` make validation declarative and reduce repetitive manual checks.

Manual validation

You can manually check fields and return a 400 Bad Request response when data is invalid.

Using a validation library

Libraries define a schema describing expected shape and constraints, then validate incoming data against it in one call.

Example 1 (javascript)
app.post('/users', express.json(), (req, res) => {
  const { name, age } = req.body;
  if (!name || typeof age !== 'number') {
    return res.status(400).json({ error: 'Invalid input' });
  }
  res.status(201).json({ name, age });
});
Output
{"error":"Invalid input"} (if age is missing/wrong type)

Manual checks reject bad input early with a 400 status.

Example 2 (javascript)
const { z } = require('zod');
const schema = z.object({ name: z.string(), age: z.number() });
const result = schema.safeParse({ name: 'Ada', age: 'old' });
console.log(result.success);
Output
false

Zod validates the shape and types of data declaratively, returning success/failure.

Key points

  • Never trust incoming client data without validation.
  • Invalid input should return a 400 Bad Request.
  • Validation libraries like Zod/Joi reduce manual boilerplate.
  • Validate as early as possible in the request lifecycle.
๐Ÿ’ก Note: Validation also helps prevent security issues like injection attacks.

๐Ÿ“ Quick Quiz

1. What status code should invalid input typically return?

2. Which of these is a schema validation library for Node.js?

3. Why validate input on the server, not just the client?