Sub topic 11
Server-side validation as the source of truth
This chapter assumes you know how an HTML form submission reaches a server, and that you have used the built-in constraint attributes and the Constraint Validation API from earlier chapters. The examples use JavaScript on the server, but the ideas apply to any language.
Why the browser's checks are not enough
Everything the browser validates runs on the user's machine, and the user controls that machine. Anyone can do the following:
- Remove
requiredorpatternin the developer tools. - Submit a form with
novalidateset. - Send a request with
curl, a script, or another program, with no browser involved. - Disable JavaScript.
Client-side validation exists for usability. It gives fast feedback and saves a round trip. It is not a security boundary. The server must treat every submitted value as untrusted input and check it again.
Repeat every rule on the server
The server should enforce every rule the form declares. If the form says minlength="3", the server checks length too. The function below mirrors the signup form from earlier in this tutorial.
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;
}Several details matter here:
String(input.email ?? '')converts a missing or non-string value into a string. A request can send an array, an object, or nothing at all, so never assume the type.trim()removes surrounding whitespace before the check. Decide whether you store the trimmed value, and keep that choice consistent.- The username pattern is anchored with
^and$. The HTMLpatternattribute is implicitly anchored, but a JavaScript regular expression is not. Without the anchors,"Bad Name!abc"would pass. Number('')is0andNumber(undefined)isNaN. Both fail the age check here, but in a form where age is optional you must handle the empty case explicitly.
The email regex is deliberately loose. It only catches obvious mistakes. The real test of an email address is sending a message to it.
Return errors the page can display
Return one message per field, keyed by field name. The client can then place each message next to its control. A typical response uses status 422 (or 400) with a JSON body. This Express handler is one way to do it.
import express from 'express';
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.post('/signup', (req, res) => {
const errors = validateSignup(req.body);
if (Object.keys(errors).length > 0) {
return res.status(422).json({ errors });
}
// Create the account here, using only the validated values.
res.status(201).json({ ok: true });
});Without JavaScript, a plain form post should get back the same form as HTML, with the submitted values refilled and the messages shown. Never refill password fields.
Validation is not the only defense
Validation checks that data has the expected shape. It does not make data safe for every place it is used. Keep these separate concerns in mind:
| Concern | Defense |
|---|---|
| Data has the wrong shape or range | Validation, as in this chapter |
| SQL injection | Parameterized queries |
| Cross-site scripting | Escape output for its context |
| Uniqueness, such as a taken username | A database unique constraint |
| Oversized requests | Body size limits in the server |
A username that passes the pattern is still not guaranteed to be free. Check uniqueness at write time and handle the database's duplicate-key error. A lookup before the insert can race with another request.
Keep rules in sync
The rules live in two places, so they can drift apart. The browser may accept a value the server rejects, which frustrates users. Reduce the drift by keeping the rules in one shared module, or by generating the HTML attributes from the same schema the server uses. When they differ, the server wins.
Exercise
A form has <input name="qty" type="number" min="1" max="10">. A user sends qty=500 with curl. What happens without server validation, and what should the server check?
Show answer
The browser's min and max never run, so the server accepts 500 and may store or act on it. The server should convert the value to a number, confirm it is an integer, and reject anything outside 1 to 10 with a field error for qty.
Exercise
Why must a JavaScript regular expression for the username be written as /^[a-z0-9_]{3,20}$/ and not /[a-z0-9_]{3,20}/?
Show answer
The HTML pattern attribute must match the whole value, but a JavaScript regex matches anywhere in the string unless it is anchored. Without ^ and $, a value such as Bad Name!abc would pass because it contains a matching substring.