Sub topic 11
Server-side validation as the source of truth
This chapter assumes you can write a basic Express-style route handler in Node.js. It also assumes you know the built-in constraint attributes, the Constraint Validation API, and how a browser sends a form as an HTTP request. Everything the browser checks, the server must check again. Here you will see why, what the server should do, and how to return errors that the page can show.
Why the browser's checks do not count
Browser validation is a convenience for the person filling in the form. It gives fast feedback without a network round trip. It does not protect your application, because the code that runs it is on the user's machine, and the user controls that machine.
Any of these skips every client-side check:
- Opening the developer tools and deleting
requiredorpatternfrom the markup. - Setting
form.noValidate = true, or callingform.submit(), which does not run validation. - Sending the request with
curl, a script, or an API client, with no browser involved. - Using an old or unusual client that does not implement a constraint, such as
type="date".
The server therefore sees what any client chooses to send. Treat every value in a request as untrusted input.
The two layers have different jobs:
| Layer | Purpose | Can be bypassed |
|---|---|---|
| Browser (attributes, API) | Speed and guidance for honest users | Yes |
| Server | Protects data integrity and security | No |
What the server should check
Mirror every rule the form declares, then add the rules the browser cannot express.
- Presence. A missing field, an empty string, and a field with only whitespace are different cases. Decide which ones count as "missing".
- Type. Form fields arrive as strings. With JSON bodies, a field can also be an array, an object, or
null. Convert deliberately, asString(input.email ?? '')does. - Format and length. Re-apply
pattern,minlength,maxlength, and the shape ofemailorurlvalues. - Range. Re-apply
min,max, andstep. - Allowed values. For a
<select>or radio group, check the value against the list you offered. A client can send any string. - Business rules. Uniqueness, permissions, and state checks (for example, "this coupon has not expired") live only on the server.
A validation function
The function below is the one from the form example. It collects errors in an object keyed by field name, so one response can describe every problem.
function validateSignup(input) {
const errors = {};
const email = String(input.email ?? '').trim();
const username = String(input.username ?? '');
const age = Number(input.age);
if (!/^[^\s@]+@[^\s@]+$/.test(email)) {
errors.email = 'Enter a valid email address.';
}
if (!/^[a-z0-9_]{3,20}$/.test(username)) {
errors.username = 'Use 3 to 20 lowercase letters, digits, or underscores.';
}
if (!Number.isInteger(age) || age < 18 || age > 120) {
errors.age = 'Age must be a whole number from 18 to 120.';
}
return errors;
}Notice three details.
- The regular expression is anchored. The HTML
patternattribute must match the whole value, as if wrapped in^(?:...)$. A JavaScriptRegExpdoes not. Without^and$, the value"Bob!"would pass/[a-z0-9_]+/. - Missing input is handled.
input.email ?? ''turnsundefinedandnullinto an empty string, so.trim()never throws. - The age rule is stricter than the form. In the HTML,
agehas norequiredattribute, so a browser accepts an empty field. On the server,Number('')is0, which fails the range check. If age is optional, say so in the server code. Otherwise the server rejects data the browser let through, and the user gets an error that the page never explained.
Keeping both sides in agreement
Rules duplicated in two places drift apart. Some ways to reduce that:
- Write the rules down once, for example as a schema object, and generate both the HTML attributes and the server checks from it.
- Share a validation module if client and server both run JavaScript.
- Add tests that send the same invalid values through the browser and through a raw request, and compare the outcomes (see the end of this chapter).
Where they still differ, the server wins. A value that is valid in the browser and invalid on the server is rejected. A value that is invalid in the browser but valid on the server is a bug in the client rules, and a user might never get to send it.
Differences in how values are counted
Some constraints are measured differently on each side.
maxlengthin browsers counts UTF-16 code units. An emoji can count as 2. A server that counts Unicode code points, bytes, or characters will disagree. Pick a rule for storage limits (usually bytes in the database column) and enforce that on the server.type="number"accepts forms such as1e3.Number('1e3')also gives1000, but a different language's parser may reject it. Parse with the rules you intend.- Browsers normalize some values. For example,
type="email"strips leading and trailing whitespace, andtype="text"removes newlines from pasted text. A raw request does none of this.
Wiring validation into a route
The route below uses Express. It parses the form body, validates it, and responds with the errors if there are any.
import express from 'express';
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
function validateSignup(input) {
const errors = {};
const email = String(input.email ?? '').trim();
const username = String(input.username ?? '');
const rawAge = String(input.age ?? '').trim();
if (!/^[^\s@]+@[^\s@]+$/.test(email)) {
errors.email = 'Enter a valid email address.';
}
if (!/^[a-z0-9_]{3,20}$/.test(username)) {
errors.username = 'Use 3 to 20 lowercase letters, digits, or underscores.';
}
if (rawAge !== '') {
const age = Number(rawAge);
if (!Number.isInteger(age) || age < 18 || age > 120) {
errors.age = 'Age must be a whole number from 18 to 120.';
}
}
return errors;
}
app.post('/signup', (req, res) => {
const errors = validateSignup(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(422).json({ errors });
}
// Safe to use the data here. Store it with parameterized queries.
res.status(201).json({ ok: true });
});
app.listen(3000);This version treats an empty age as "not provided", which matches the HTML form. Here is a request that never touches a browser:
curl -i -X POST http://localhost:3000/signup \
-d "email=not-an-email" \
-d "username=Bad Name!" \
-d "age=7"The server answers with status 422 and a JSON body naming all three fields:
{
"errors": {
"email": "Enter a valid email address.",
"username": "Use 3 to 20 lowercase letters, digits, or underscores.",
"age": "Age must be a whole number from 18 to 120."
}
}Choosing a status code
Use a 4xx status for invalid input, never 200. A 200 tells clients, caches, and monitoring tools that the request worked.
400 Bad Requestis the general choice for malformed input.422 Unprocessable Contentsignals that the request was well formed but its values failed validation. Many APIs use it for field errors.409 Conflictsuits a uniqueness failure, such as a username that is taken.
Pick one convention and keep it across the application.
Returning errors the page can use
A good error response is specific, complete, and safe.
- Key errors by field name. The page can then place each message beside the control it belongs to. In the earlier chapter on accessible errors, each control had an element with the id
<field.id>-error, so the key and the id should line up. - Return all errors at once. Making users fix one problem per submission is frustrating.
- Write messages for people. "Use 3 to 20 lowercase letters, digits, or underscores" helps. "Pattern mismatch" does not.
- Give the user their input back. For a full-page form post, render the form again with the submitted values filled in and the errors beside each field. Do not echo passwords.
- Do not leak internals. Never include stack traces, SQL, or file paths in a validation response.
For a JavaScript-enhanced form, you can read the errors object and feed it into the same display code the browser path uses. Setting setCustomValidity with a server message and then calling reportValidity also works, but remember to clear the message on the next input event, or the field stays invalid forever.
const form = document.getElementById('signup');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const response = await fetch(form.action, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(new FormData(form)),
});
if (response.status === 422) {
const { errors } = await response.json();
for (const [name, message] of Object.entries(errors)) {
const field = form.elements[name];
if (!field) continue;
field.setCustomValidity(message);
field.addEventListener('input', () => field.setCustomValidity(''), { once: true });
}
form.reportValidity();
}
});Validation is not the same as safe output
Valid input is not automatically safe input. Validation answers "is this value acceptable?" It does not make the value harmless wherever it goes next.
- Use parameterized queries for the database, even for values that passed validation.
- Escape on output for the context where the value is shown (HTML, attribute, URL, JavaScript).
- Do not rely on a blocklist of "bad characters". Names like
O'Brienare valid. Prefer allowing what you expect and encoding at the point of use.
Edge cases to plan for
- Extra fields. A request can include fields your form never had, such as
isAdmin=true. Copy only the fields you expect into your data object, and never pass the raw body to your database layer. - Repeated fields.
username=a&username=bmay arrive as an array.String(['a','b'])becomes"a,b", which then fails your pattern. This is usually the result you want, but make sure no code path assumes a string. - Large bodies. Limit the body size at the server (Express's
express.json({ limit: '100kb' })) so oversized requests are rejected before validation runs. - File uploads. Check size and type on the server, and do not trust the filename or the
Content-Typethe client claims. - Rate limits. Validation does not stop a script from sending thousands of valid requests. Limit requests per client separately.
Exercise
A signup form has <input name="username" required minlength="3" pattern="[a-z0-9_]+">. The server checks it with /[a-z0-9_]+/.test(username) and a separate length check. A user sends username=ab%21%21%21 with curl, which decodes to ab!!!. Does the server accept it, and what is the fix?
Show answer
The server accepts it. The regular expression is not anchored, so it matches the substring ab and ignores the !!!. The HTML pattern attribute is implicitly anchored, so the browser would have rejected it, which hides the difference. The fix is to anchor the expression: /^[a-z0-9_]{3,20}$/, or add ^ and $ to the existing one.
Exercise
Your form lets the browser accept an empty optional age field, but your server runs Number(input.age) and rejects 0. What goes wrong for the user, and how do you correct it?
Show answer
Users who leave the optional field empty pass browser validation, then get an unexplained error from the server, because Number('') is 0 and fails the range check. Treat an empty string as "not provided" on the server and validate only when a value is present, so the two layers agree.