Sub topic 1
Why validate forms, and where
This chapter explains what form validation is for, where it can run, and why the browser's checks never replace the server's. Later chapters cover the attributes, the API, and the server code in detail.
Prerequisites
This chapter assumes you know the following:
- Basic HTML: forms, labels, and input elements.
- Basic CSS selectors.
- Basic JavaScript: selecting elements and handling events.
- How an HTTP form submission sends data to a server.
You do not need to know any validation attributes or APIs yet.
What validation is
Form validation is the process of checking that submitted data is acceptable before the application uses it. "Acceptable" covers several different questions:
- Presence: is a required value there at all?
- Shape: does it look like an email address, a date, or a whole number?
- Range and length: is the age between 18 and 120? Is the username 3 to 20 characters?
- Relationships: do the password and its confirmation match? Does the end date come after the start date?
- Business rules: is the username already taken? Does the coupon exist and still apply?
The first three are cheap to check anywhere. The last two often need information the browser does not have, such as data in a database.
Two goals: usability and security
Validation serves two separate goals, and they pull in different directions.
Usability means helping an honest person finish the form. A browser check can tell someone about a typo in their email address immediately, without a round trip to the server. The message appears next to the field, and the person fixes it and moves on. For this goal, speed and clear wording matter most.
Security and data integrity mean protecting the system from bad input, whether it is malformed, hostile, or merely unexpected. For this goal, only checks that an attacker cannot skip are useful.
Client-side validation (code running in the user's browser) serves the first goal well. It cannot serve the second, because the client is controlled by whoever is using it.
Where validation can run
There are three common places to validate, and each has a different role.
| Layer | Examples | Strengths | Weaknesses |
|---|---|---|---|
| Browser, built-in | `required`, `type="email"`, `pattern` | No JavaScript needed, instant feedback, localized messages | Limited rules, easy to bypass |
| Browser, scripted | Constraint Validation API, custom handlers | Any rule you can code, custom messages and layout | Easy to bypass, depends on JavaScript running |
| Server | Request handler, framework validators, database constraints | Cannot be bypassed by the client, can use stored data | Needs a round trip, so feedback is slower |
A fourth layer sits behind the server: database constraints such as NOT NULL, UNIQUE, and foreign keys. They are the last line of defence. They catch race conditions and bugs that slip past application code, but their error messages are rarely suitable to show a user directly.
Why the client cannot be trusted
Browser validation runs on a machine you do not control. Anyone can get around it, and no special skill is needed. Here are the common ways.
- Disable or edit the page. In the browser's developer tools, a user can delete the
requiredattribute, changemaxlength, or addnovalidateto the form. - Turn off JavaScript. Scripted checks then never run.
- Send the request directly. A form submission is just an HTTP request. Tools such as
curlor a script can send any body to your endpoint without loading your page. - Use an old or unusual client. Some browsers, embedded views, and bots handle validation attributes differently or not at all.
The following command submits values that the form in this tutorial would reject in the browser. The server still receives them:
curl -X POST https://example.com/signup \
-d "email=not-an-email" \
-d "username=A very long username with spaces and capitals" \
-d "age=-5"No browser is involved, so no browser check runs. If your server accepts this request, your validation does not exist as far as an attacker is concerned.
Not every bypass is malicious. A browser extension, an autofill tool, or a mobile app that reuses your API can also send values your page would never produce. A server that validates everything handles all of these the same way.
The request path
The diagram shows where each check sits and which requests skip the browser.
Both routes meet at the server. Only the server's check applies to both.
What belongs where
A useful way to decide is to ask what each check is for.
- Browser checks: anything that helps a person correct a mistake quickly. Missing fields, wrong formats, out-of-range numbers, and mismatched passwords are all good candidates.
- Server checks: every rule that matters for correctness or safety, repeated in full. This includes all the rules you already put in the browser.
- Server-only checks: rules that need data or secrets the client should not have, such as whether an email is already registered, whether a user may perform an action, or whether a coupon is valid.
Duplicating rules looks wasteful, but the two copies do different jobs. If the browser copy is wrong, a user sees a confusing message. If the server copy is wrong or missing, you have a vulnerability.
Keep the rules consistent
Duplication creates a risk of drift. The browser might accept 2 to 30 characters while the server accepts 3 to 20. A user then sees a field marked valid, submits, and gets a server error. To reduce drift:
- Write the rules once in a shared description where you can, such as a schema that both sides read.
- Where you cannot share them, put the numbers in one clearly named place on each side.
- Make the server the stricter or equal side, never the looser side.
- Test the pair together. A later chapter covers testing.
Validation is not sanitization or escaping
Validation answers "is this input acceptable?" It is not a complete defence against injection attacks, and it should not be confused with two related techniques.
- Sanitization changes input to make it safe or consistent, for example trimming whitespace.
- Escaping or parameterizing makes sure data cannot be read as code in a particular context. Use parameterized queries for SQL and escape output for HTML.
Validation narrows what comes in, which reduces risk. It does not replace the context-specific handling above. A name field that allows apostrophes, such as "O'Brien", is valid input and still must be passed to the database through a parameterized query.
Rules that are too strict
Validation can also fail the user by rejecting valid data. Common mistakes:
- Names: requiring only ASCII letters rejects many real names. Hyphens, apostrophes, spaces, and non-Latin scripts are all normal.
- Email addresses: a precise pattern for every legal address is extremely complicated. The simple check that the value has an
@with text on both sides is usually enough. The only real proof an address works is sending a message to it. - Phone numbers and postal codes: formats differ by country. A rigid pattern rejects valid numbers abroad.
- Whitespace: a pasted value with a trailing space fails a strict rule. Trim values before checking them where that is appropriate.
When a rule is uncertain, prefer accepting a doubtful value and verifying it another way over rejecting a real user.
A first look at the layers in code
The next chapters build this up properly. Here is the shape of it, so that the layers are concrete.
This markup asks the browser to check a username before submission:
<form action="/signup" method="post">
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+">
<button type="submit">Sign up</button>
</form>The browser blocks an empty or too-short username and shows a message. This server function applies the same rule to data that arrives, however it was sent:
function validateUsername(value) {
const username = String(value ?? '');
if (!/^[a-z0-9_]{3,20}$/.test(username)) {
return 'Use 3 to 20 lowercase letters, digits, or underscores.';
}
return null;
}
console.log(validateUsername('ab')); // error message
console.log(validateUsername('good_name')); // null
console.log(validateUsername(undefined)); // error messageNotice that the server function converts the value to a string first. A direct request can send a missing field, a list, or a different type, and the code must not assume the shape that your form produces.
Common mistakes
- Treating the browser check as the real check. The server must validate every field.
- Validating only some fields on the server. Attackers target the one you skipped.
- Trusting hidden fields and disabled controls. Hidden inputs, select options, and radio values can all be changed. Check that a submitted choice is one you offered.
- Showing the same error for every failure. "Invalid input" helps no one. Say which field failed and what is expected.
- Rejecting on the client without telling the user why. A blocked submit with no visible message is confusing and inaccessible.
- Returning only the first server error. Return all field errors so the user can fix them in one pass.
Summary of the plan
The rest of this tutorial follows the layers in order. First come the built-in attributes and input types, then how the browser reports errors, then the Constraint Validation API for custom behavior. After that come styling and accessible messages, then cross-field and asynchronous checks. The server-side chapter returns to the rules in this chapter and shows how to apply them to every request.
Exercise
A signup form marks the username field with required, minlength="3", and pattern="[a-z0-9_]+". A teammate says the server does not need to check the username, because the browser already does. Give two concrete ways a request with a 1-character username could still reach the server, and state what the server should do.
Show answer
Any two of these work. A user can delete the required, minlength, or pattern attributes in the browser's developer tools and submit. A user can add novalidate to the form. A user can disable JavaScript or use a browser that does not enforce the attributes. A user or script can skip the page and send the request directly with a tool such as curl. The server should validate the username itself on every request. It should convert the value to a string, apply the same length and character rules, and reject the request with a clear error for the username field.
Exercise
A form lets users pick a country from a select element that lists 20 options. Is it enough for the server to trust that the submitted value is one of those 20? Explain, and say what the server should check.
Show answer
No. The select element only limits what the page offers. A user can edit the options or send a direct request with any value. The server should compare the submitted value against its own list of allowed countries and reject anything that is not on it.
Exercise
Your browser rule allows usernames of 2 to 30 characters, but the server allows 3 to 20. Describe what a user experiences with a 25-character username, and give one way to prevent this kind of drift.
Show answer
The browser accepts the username and lets the form submit, then the server rejects it, so the user sees an unexpected error after they believed the field was valid. To prevent drift, define the limits in one shared place such as a schema that both sides use, or at least keep the numbers in one named location per side. Make the server rule at least as strict as the browser rule, and test both together.