Forms and Validation
Collect input the right way: labelled fields, the right input types, built-in validation attributes, the Constraint Validation API, accessible error messages, and why the server must validate again. Practise by building a sign-up form with a password check.
1. Forms are where users give you things
Sign-ups, log-ins, search, checkout, comments: forms are how a page collects data. They are also where many sites lose people, through confusing labels, over-strict rules and errors that do not explain what is wrong. A good form is easy to read, easy to fill and kind about mistakes.
2. The anatomy of a good field
<form action="/signup" method="post">
<div class="field">
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required>
</div>
<div class="field">
<label for="pw">Password</label>
<input id="pw" name="password" type="password" autocomplete="new-password" minlength="8" required aria-describedby="pw-help">
<small id="pw-help">At least 8 characters.</small>
</div>
<button type="submit">Create account</button>
</form>
<label for="id">connects the label text to the field with thatid. Clicking the label focuses the field, and screen readers announce it. (You can also wrap the input inside the label.) A placeholder is not a label: it vanishes when typing starts and is often low contrast.nameis the key the server receives (email=...&password=...). A field without anameis not submitted.typepicks the right behaviour and keyboard.autocompletelets browsers and password managers fill the field correctly (email,new-password,current-password,one-time-code,given-name,postal-codeand so on). It helps everyone, and is required for accessible sign-in under WCAG.<button type="submit">submits; usetype="button"for buttons that should not.
3. Choosing input types
| Type | Gives you |
|---|---|
text |
Free text |
email |
Email keyboard on phones, basic address check |
password |
Masked input |
number |
Numeric input with min, max, step |
tel |
Phone keypad (no validation: phone formats vary) |
url |
URL keyboard and check |
date, time, datetime-local |
Native pickers |
checkbox / radio |
On-off, or one choice from a group (radios share a name) |
file |
File upload (accept, multiple) |
search |
Search box semantics |
hidden |
Data that the user cannot edit (never put secrets here: anyone can change it) |
Other controls: <textarea> for multi-line text, <select> with <option> for a list, <fieldset> and <legend> to group related fields (such as a set of radio buttons), and <datalist> for suggestions.
4. Built-in validation
HTML can check input with no JavaScript:
| Attribute | Rule |
|---|---|
required |
A value must be present |
minlength / maxlength |
Text length |
min / max / step |
Number or date range |
pattern="[A-Za-z0-9_]{3,20}" |
Must match a regular expression (with a title that explains it) |
type="email", type="url" |
Format checks |
The browser blocks submission, focuses the first invalid field and shows a message. Style states with :invalid, :valid, :required and :user-invalid (which only applies after the user has interacted, so people are not shouted at before they type).
5. The Constraint Validation API
For rules HTML cannot express (passwords match, a username is not taken), JavaScript works with the same system:
const form = document.querySelector('form');
const pw = form.elements.password;
const confirm = form.elements.confirm;
confirm.addEventListener('input', () => {
confirm.setCustomValidity(confirm.value === pw.value ? '' : 'Passwords do not match.');
});
form.addEventListener('submit', (e) => {
if (!form.checkValidity()) { // built-in and custom rules together
e.preventDefault();
form.reportValidity(); // show the browser's messages
}
});
setCustomValidity('message') marks the field invalid with that message; setting it to an empty string clears the error. checkValidity() returns true or false, reportValidity() also shows the messages, and field.validity tells you why (valueMissing, typeMismatch, tooShort, patternMismatch …).
If you want fully custom error text and styling, add novalidate to the <form> and handle it yourself. Then you take on the accessibility work.
6. Error messages people can use
- Say what is wrong and how to fix it: “Password must be at least 8 characters”, not “Invalid input”.
- Place the message next to the field and connect it with
aria-describedby; setaria-invalid="true"on the field. - Do not rely on colour alone. Add text and an icon.
- Validate on submit and after leaving a field (
blur), not on every keystroke while someone is still typing. - Keep what they typed, and move focus to the first error (or an error summary at the top) so keyboard and screen-reader users find it.
- Do not use
alert()for errors: it blocks the page and is poorly announced.
<label for="user">Username</label>
<input id="user" name="user" aria-describedby="user-err" aria-invalid="true">
<p id="user-err" class="error" role="alert">Usernames use 3 to 20 letters, digits or underscores.</p>
7. Never trust the browser
Everything above runs in the visitor’s browser, where they control it. Anyone can delete required, edit the HTML in DevTools, or send a request with curl without ever loading your page. So:
- Client-side validation is for usability.
- The server must validate every field again and decide what is allowed (type, length, range, format, business rules). This is the single most important rule of form handling.
- Protect state-changing forms against CSRF (a token or a
SameSitecookie), and never include secrets in hidden fields. - Treat file uploads as hostile: check type and size on the server.
8. Your turn: a sign-up form with a password check
Complete the form so that:
- Each input has a label connected with
forandid. - The email field has
type="email"and is required. - The password field is required with
minlength="8". - There is a confirm password field (
name="confirm"). - When the form is submitted with passwords that do not match, your script stops the submission and writes a message containing the word match into the element with id
error.
Your tasks
- ○The email input has type="email"
- ○The email input is required
- ○The password input is required and has minlength 8
- ○There is a confirm password field (name="confirm", type="password")
- ○Every input has a label connected to it
- ○Mismatched passwords are caught: the submission is stopped and #error says they do not match
9. What you learned
You labelled every field, picked input types that give users the right keyboard and checks, used built-in and custom validation, and wrote error messages that people (and screen readers) can use. And you know that the real validation belongs on the server. Next: making every page usable by everyone.
🧪 Want to practise this on your own computer? See how to set up your lab →