Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 43 ยท Building REST APIs

Validating Input

Validate Express request bodies, params and queries: manual checks, Zod and Joi schemas, express-validator, reusable validation middleware and 422 responses.

Everything that arrives in req.body, req.params, req.query and req.headers comes from outside your program, so you cannot trust it. A client might send a number where you expect text, forget a field, send a 10 MB string, or try something hostile. Validation means checking that input has the shape and values your code expects before the controller or service uses it.

Good validation gives callers clear feedback (which field is wrong and why), protects your database, and lets the rest of your code assume its inputs are sane. This lesson starts with plain checks, then shows how schema libraries scale the idea, and finally builds a reusable validation middleware.

Real libraries (Zod, Joi, express-validator) need npm, so they appear as read-only code. The runnable examples use a small hand-written validator with the same ideas, on the stand-in framework from Inside Express.

Validate, then trust

Where input comes from

req.body JSON or form data from the client.
req.params Pieces of the URL path, always strings.
req.query The query string, always strings.
Headers Tokens, content types, versions.

All of it is untrusted until checked.

1 / 2

Two details matter right away. First, req.params and req.query values are always strings (or arrays of strings for repeated query keys), so ?page=2 gives you "2", not 2. Convert and check them. Second, a missing body is not an empty object: in Express 5, req.body is undefined when no body parser ran or the request had no body, so req.body.title would throw a TypeError. Guard against it.

Manual validation

The simplest validation is a handful of if statements inside the handler.

JavaScript
app.post('/todos', (req, res) => {
  const { title, priority } = req.body ?? {};
  const problems = [];

  if (typeof title !== 'string' || title.trim() === '') {
    problems.push({ field: 'title', message: 'Title is required.' });
  }
  if (priority !== undefined && !['low', 'medium', 'high'].includes(priority)) {
    problems.push({ field: 'priority', message: 'Use low, medium or high.' });
  }

  if (problems.length > 0) {
    return res.status(422).json({ errors: problems });
  }
  // ... safe to continue
});

This is fine for one route. It becomes noisy when ten routes repeat the same patterns, and the checks are mixed into the controller. Notice two good habits already: collect all problems instead of stopping at the first, and answer with a structured error list.

400 or 422?

Both are used in practice. 400 Bad Request means the request could not be understood at all (for example malformed JSON). 422 Unprocessable Content means the request was well-formed but its values are not acceptable. Many APIs use 422 for validation failures, and so does this course; whichever you choose, use it consistently. Designing a REST API covers status codes in more detail.

Validation as middleware

Since validation is about the request and not about business logic, it fits naturally in middleware that runs before the controller. If the input is invalid it answers immediately and never calls next(); otherwise the controller runs with clean data.

The next example builds a tiny schema validator. A schema is an object that describes each field, and validate(schema) turns it into a middleware. It trims strings, converts numbers, applies defaults, reports every problem, and keeps only the fields the schema knows about.

Node.js A hand-written validator and middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the first call the title is trimmed, "2.5" becomes the number 2.5, the default priority is added, and the unknown isAdmin field is silently dropped. The second and third calls return a 422 with every problem listed. The unknown-field behavior is important: copying req.body straight into a database record lets clients set fields like isAdmin themselves, a flaw called mass assignment.

Validating params and queries

The same middleware idea works for the other inputs. Since they are strings, conversion is part of the job. This example checks the id path parameter and the page and limit query values, giving defaults when they are missing.

Node.js Params and query strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice toInt rejects anything that is not plain digits. Number('') is 0 and Number('1e3') is 1000, so converting blindly accepts values nobody intended.

Schema libraries in real projects

Writing validators by hand is good for understanding, but in a real project you would use a library. All of the following are installed with npm, so their code is read-only on this site.

Zod describes the schema in TypeScript-friendly code and also infers types:

JavaScript
import { z } from 'zod';

const createTodoSchema = z.object({
  title: z.string().trim().min(3).max(40),
  priority: z.enum(['low', 'medium', 'high']).default('medium'),
  estimateHours: z.coerce.number().min(0).max(100).optional(),
});

const validateBody = (schema) => (req, res, next) => {
  const result = schema.safeParse(req.body);
  if (!result.success) {
    return res.status(422).json({ errors: result.error.issues });
  }
  req.body = result.data;
  next();
};

safeParse returns a result instead of throwing, and by default Zod drops unknown keys from result.data.

Joi has a similar chained style:

JavaScript
import Joi from 'joi';

const schema = Joi.object({
  title: Joi.string().trim().min(3).max(40).required(),
  priority: Joi.string().valid('low', 'medium', 'high').default('medium'),
});

const { value, error } = schema.validate(req.body, { abortEarly: false, stripUnknown: true });

Without abortEarly: false Joi stops at the first problem; without stripUnknown it rejects extra keys.

express-validator wraps the validator.js library as middleware chains instead of schemas:

JavaScript
import { body, validationResult } from 'express-validator';

app.post(
  '/todos',
  body('title').trim().isLength({ min: 3, max: 40 }),
  body('priority').optional().isIn(['low', 'medium', 'high']),
  (req, res) => {
    const result = validationResult(req);
    if (!result.isEmpty()) {
      return res.status(422).json({ errors: result.array() });
    }
    res.status(201).json({ ok: true });
  },
);

Which to pick? Zod is popular with TypeScript projects. Joi is mature and very flexible. express-validator feels natural if you like middleware chains. All three give the same practical result: a clear error list and clean data.

Validation is not the only defense

Validation checks shape and plausibility. It does not replace:

  • Parameterized queries, which stop SQL injection even for valid-looking text (Security Best Practices).
  • Output escaping when you render user text into HTML.
  • Database constraints such as unique indexes, because two simultaneous requests can both pass validation.
  • Body size limits on express.json({ limit: '100kb' }) (Built-in Middleware).

Validate on the server even if your front end validates too. Browser checks are for the user's convenience; anyone can send requests directly with curl or a script.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What type are the values in req.query?

    The query string is text. "2" stays the string "2" until you convert and check it.
  2. 2. Which status code do many APIs (and this course) use for well-formed requests with invalid values?

    422 Unprocessable Content signals that the request was understood but its values are not acceptable. 400 is typical for unparseable requests.
  3. 3. Why should a validator drop fields that are not in the schema?

    Copying unknown fields into records lets clients set properties they should never control.
  4. 4. Where does a validation middleware sit relative to the controller?

    Validation runs first and either answers with an error or passes clean data on with next().
  5. 5. Does client-side validation make server-side validation unnecessary?

    Anyone can call your API without your front end, so the server must validate everything itself.

Summary

  • Treat req.body, req.params, req.query and headers as untrusted; params and query values are strings.
  • Collect all problems, answer with a structured list and a consistent status (422 or 400).
  • Put validation in middleware before the controller, and replace req.body with the cleaned data.
  • Drop unknown fields to prevent mass assignment.
  • Zod, Joi and express-validator do this at scale; validation complements, but does not replace, parameterized queries and output escaping.

Next: Error Handling.