You fill in a sign-up form, click Sign up, and red text appears under two boxes: "Email is required" and "Password must be at least 8 characters". The boxes you got right stay filled in. That red text often comes from the server. The server checks what you sent first, refuses what's wrong, and tells you which boxes need fixing.
This check is called input validation: checking the data the client sent before that data is used. What gets checked: required fields are there, the types are right, and the values make sense. Think of a clerk at a counter who checks forms. If a box is empty or wrong, the form goes back with a note next to each wrong box. The clerk doesn't accept a wrong form and file it, because the files would become a mess. In an API, the clerk is the server, the form is the request, and the note next to each box is an error message for each field in the response.
Why the server still has to check
The form on the Bookshop website may already refuse a negative price. But that form is only one way in. Anyone can send a request straight to the API with curl or Postman, without the form. So validation in the frontend can be bypassed (skipped). The frontend is the part that shows in the browser, such as that form. Validation in the frontend is there for the user's comfort, while validation on the server is the last line of defence. Remember POST /greet in the lesson Your First Endpoint, which answered "Hello, undefined!" when no name was sent? That was an endpoint with no validation.
The rules for a new book
These are the rules for a new book sent with POST /books:
| Field | Rule |
|---|---|
title |
required, text, at least 2 characters |
price |
required, a whole number, at least 0 |
stock |
required, a whole number, at least 0 |
The code below checks those three rules before it saves the book:
app.post("/books", (req, res) => {
const { title } = req.body;
const errors = {};
if (title === undefined || title === "") {
errors.title = ["The title field is required."];
} else if (typeof title !== "string") {
errors.title = ["The title field must be a string."];
} else if (title.trim().length < 2) {
errors.title = ["The title field must be at least 2 characters."];
}
for (const field of ["price", "stock"]) {
const value = req.body[field];
if (value === undefined) {
errors[field] = [`The ${field} field is required.`];
} else if (!Number.isInteger(value)) {
errors[field] = [`The ${field} field must be an integer.`];
} else if (value < 0) {
errors[field] = [`The ${field} field must be at least 0.`];
}
}
if (Object.keys(errors).length > 0) {
return res.status(422).json({ message: "The given data was invalid.", errors });
}
// Every rule passed: only now is it saved, as in the CRUD lesson.
const book = { ...req.body, id: nextId++ };
books.push(book);
res.status(201).json(book);
});
errorsstarts as an empty object. Each field that fails adds a key with that field's name. So every mistake is collected, instead of stopping at the first one.typeof title !== "string"checks whethertitleis text. This check runs before.trim(), because a number has no.trim().title.trim()removes spaces at the start and the end, so" "doesn't count as 2 characters.Number.isInteger(value)is onlytruefor a whole number:95000passes, while"95000"(text) and95000.5are refused.Object.keys(errors).length > 0means there's at least one error.returnstops the handler, so wrong data never reachesbooks.push.{ ...req.body, id: nextId++ }at the end still saves every field that was sent. That includes fields that are not in the rules table, for example"is_featured": true. Validation checks the fields you name, but it does not remove the others. In a real API, build the book only from the checkedtitle,priceandstock(remember the mass assignment hole in the CRUD API lesson).
Don't rely on truthy
A value that if treats as true is called truthy, and one that if treats as false is called falsy. 0, "", false, null and undefined are all falsy. So if (!req.body.stock) refuses "stock": 0, even though 0 is a valid stock. The book This Earth of Mankind, which really is sold out, gets refused too.
A proper check says what it means: "not sent" is value === undefined, "not a whole number" is !Number.isInteger(value), "negative" is value < 0. With these checks, 0 passes and -5000 is refused.
422 or 400?
Both mean "the sender got it wrong", but the kind of mistake is different:
400 Bad Request: the request itself is broken, so the server can't read it. Example: the body{"title": "This Earth of Mankind",with its curly brace never closed. Express refuses it with 400 before your handler runs.422 Unprocessable Content: the request can be read and the JSON is correct, but what it says breaks the rules. Example:{"title": "A", "price": -5000, "stock": 0}. Its old name is Unprocessable Entity, and Node still writes that old name. The code is still the same: 422.
Many APIs, Laravel (a popular PHP framework) included, answer a failed validation with 422, and the exercise in this lesson uses 422 too. Some other APIs use 400 for all wrong input. In the Request & Response lesson, the Bookshop answered a missing required field with 400. In this lesson, the Bookshop follows Laravel, so a missing title also gets 422. What matters is that you send a 4xx code. Never send 200, because the client thinks it worked, and never 500, because that means the server is broken.
The error shape, per field
For the body {"title": "A", "price": -5000, "stock": 0}, the server above answers:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json; charset=utf-8
This is the body, laid out neatly so it's easy to read:
{
"message": "The given data was invalid.",
"errors": {
"title": ["The title field must be at least 2 characters."],
"price": ["The price field must be at least 0."]
}
}
messageis a one-sentence summary.- The keys in
errorsare field names, and each holds a list of messages. The frontend just puts each message under the box in the form with the same name. stock: 0passes, so it doesn't appear inerrors.
In Laravel
In Laravel, the three book rules above are written like this:
$validated = $request->validate([
'title' => 'required|string|min:2',
'price' => 'required|integer:strict|min:0',
'stock' => 'required|integer:strict|min:0',
]);
That one validate call does every check above. Note the :strict. Without :strict, integer also accepts the text "95000", which the JavaScript check above refuses. integer:strict accepts only real whole numbers from the JSON. An HTML form always sends text, so for a form, use plain integer. If any rule fails, Laravel answers 422 with the same body shape by itself. Its message is taken from the first error: "The title field must be at least 2 characters. (and 1 more error)". A POST /api/students request missing the required field name is answered 422 too.
$validated holds only the fields named in the rules. Any other field, for example is_featured, is dropped. So save $validated (Book::create($validated)), not $request->all() (every field that was sent). A model is a Laravel class for one kind of data, such as Book. The model is a second guard: its $fillable property lists the fields that create() may fill.
⚠️ Checks that catch the wrong thing or answer the wrong way
- A truthy check for a number.
if (!stock)refuses 0. Writestock === undefinedor!Number.isInteger(stock). - Stopping at the first error. With a
returnin everyif, the client only learns about the next mistake after fixing the first. Collect every mistake inerrorsfirst, then answer once. - Answering a failed validation with 200 or 500.
res.json({ error: "..." })answers 200, so the client thinks it worked. Useres.status(422)(or400if the API uses 400). - Laravel answers 302, not 422. Without the header
Accept: application/json, Laravel assumes the request came from an HTML form. Laravel then redirects (sends) the client back to the page before. An API client has to send that header.
TL;DR: Input validation is checking the data the client sent before it is used. Validation on the server is a must, because validation in the frontend (the form in the browser) can be bypassed with curl or Postman. Check each field (required, type, length or value). Collect every mistake in an errors object whose keys are field names, then answer once, for example {"message": "...", "errors": {"title": ["..."]}}. A broken body that can't be read: 400 Bad Request. A body that can be read but breaks the rules: 422 Unprocessable Content (Laravel and this exercise use it). Don't use a truthy check for numbers, such as if (!stock): 0 is falsy (if treats it as false), so write === undefined and Number.isInteger. In Laravel (a PHP framework), $request->validate([...]) answers 422 by itself, as long as the client sends Accept: application/json.
⚡ The server still has to check
Guess first: the form on the Bookshop website already refuses a negative price. Does the server still need to check?
Yes. That form is only one way in. Anyone can send a request straight to the API with curl or Postman, without the form.
Meaning: Checking the data the client sent before it is used is called input validation. Validation in the frontend (the form in the browser) can be bypassed (skipped). It's there for the user's comfort, while validation on the server is the last line of defence.
⚡ Collect every mistake, answer once
Write:
const errors = {};
if (title === undefined || title === "") {
errors.title = ["The title field is required."];
}
if (Object.keys(errors).length > 0) {
return res.status(422).json({ message: "The given data was invalid.", errors });
}
Meaning: errors starts as an empty object. Each field that fails adds a key with that field's name, so every mistake is collected. If errors isn't empty, the server answers 422 (the request can be read but breaks the rules) with every message at the same time. return stops the handler, so wrong data never reaches books.push, the line that saves the book.
⚡ Don't rely on truthy
Guess first: does if (!req.body.stock) refuse "stock": 0?
It does. 0 is falsy: if treats it as false. But 0 is a valid stock. A book that really is sold out, such as This Earth of Mankind, gets refused too.
Meaning: A check like if (!req.body.stock) refuses every falsy value, 0 included. So write a check that says what it means: value === undefined for "not sent", !Number.isInteger(value) for "not a whole number".
⚡ 400 or 422
Meaning: 400 is for a broken request that can't be read. 422 is for a request that can be read but breaks the rules, such as a negative price. Never 200 (the client thinks it worked) and never 500 (that means the server is broken).