Lesson 6 of 52HTML
Forms
Collect input with labels, the right input types, built-in validation and a clear idea of what happens when a form is sent.
Almost every useful site asks you for something: a search term, an email address, a delivery date, a password. HTML forms are how pages collect that input, and the browser gives you a lot for free if you use the right elements. You get mobile keyboards that match the field, date pickers, error messages and keyboard support without writing a line of JavaScript. Getting forms right is also one of the biggest accessibility wins on any site, because a confusing form is a closed door.
The form element and its job
A form is a group of fields that are sent together. The form element wraps them and says where the data goes and how.
<form action="/subscribe" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email">
<button type="submit">Subscribe</button>
</form>Three attributes matter on the form itself:
actionis the address the data is sent to. Leave it out and the form sends to the current page.methodis how it is sent:getorpost(more on these at the end of the lesson).- Each field inside needs a
name. The name is the key the server receives, likeemail=sam@example.com. A field without anameis simply not sent.
Think of a paper form at a doctor's office. The label printed next to each box tells you what to write, the name is the column the receptionist types it into later, and the value is what you actually wrote.
Labels: the most important part
A label is the visible text that describes a field. Linking a label to its field does three things: screen readers announce the label when the field gets focus, clicking the label focuses the field (a bigger target, great on phones), and the connection is clear to everyone.
There are two ways to link them:
<!-- 1. The for attribute matches the input's id -->
<label for="city">City</label>
<input id="city" name="city">
<!-- 2. Wrap the input inside the label -->
<label>
<input type="checkbox" name="news"> Send me the newsletter
</label>A placeholder is not a label. It is faint hint text that disappears as soon as someone types, so the learner who looks away and back has lost the question. Use placeholders for examples ("e.g. 10115"), never as the only description.
Preview
Click the words "Your name" and watch the cursor jump into the field. Now change for="name" to for="nope" and click again: the link is broken and nothing happens. Then click the text "Send me the newsletter" and see the checkbox toggle, because the input sits inside its label.
placeholder='Email' on its input and has no label. What is the main problem?Input types
The input element is a void element (it has no closing tag) that changes shape based on its type. Choosing the right type costs nothing and gives you the right phone keyboard, built-in checks and native pickers.
| Type | What it gives you |
|---|---|
text | The default single-line box |
email | Email keyboard on phones, checks for an @ and a domain |
password | Hides the characters as you type |
number | Numeric keyboard, up and down arrows, works with min, max, step |
date | A native date picker |
checkbox | An on or off choice; several can be ticked |
radio | Pick exactly one from a group that shares a name |
range | A slider between min and max |
file | A button to choose files from the device |
Not every multi-line or multiple-choice field is an input:
textareais a multi-line text box with a closing tag. Use it for messages and comments.selectwithoptionchildren is a drop-down list. Each option has avaluethat gets sent, and the text between the tags is what people see.
Preview
Try these one at a time: change type="number" to type="range" and you get a slider. Change one radio's name to menu2 and notice you can now pick both, because radios only form a group when they share a name. Add a third option to the select.
One more attribute saves people a lot of typing: autocomplete. Values like autocomplete="email", "name", "street-address" and "new-password" tell the browser and password managers exactly what a field is for, so they can fill it in correctly. It is a small kindness for everyone and a big help for people who find typing slow or painful.
autocomplete tokens
autocomplete is not on or off. Its value is a token from a fixed list in the HTML standard, and the browser uses it to decide which saved value goes where. Get the token right and a checkout that took two minutes takes ten seconds. Get it wrong and the browser fills a surname into the city field, which is worse than filling nothing.
| Field | Token |
|---|---|
| Full name | name (or given-name and family-name for two fields) |
| Email on a sign-up or contact form | email |
| Login identifier (email or username) | username |
| Password on a login form | current-password |
| Password on sign-up or "change password" | new-password |
| SMS or app code | one-time-code |
| Phone | tel |
| Address in one textarea | street-address |
| Address in separate lines | address-line1, address-line2 |
| Postcode or ZIP | postal-code |
| Card number, expiry, name on card | cc-number, cc-exp, cc-name |
Three details separate a working form from one that only looks right:
- The password tokens tell password managers what to do.
current-passwordmeans "offer the saved one".new-passwordmeans "offer to generate a strong one and save it". A sign-up form markedcurrent-passwordgets no generated password, and a login form markednew-passwordgets a pop-up offering a new password to someone who only wants to log in. - Prefixes separate two addresses.
autocomplete="shipping postal-code"andautocomplete="billing postal-code"let the browser fill two different addresses on one page. autocomplete="off"is not a fix. Browsers often ignore it on login and address fields, and where they honour it, it blocks the password manager that helps people use strong passwords. Use the right token instead. For passkeys,autocomplete="username webauthn"on the login field lets the browser offer saved passkeys in the same autofill list.
This is also a legal requirement in many places. WCAG success criterion 1.3.5 Identify Input Purpose (level AA) says fields that collect the user's own details must expose their purpose in code, and the autocomplete token is how you meet it. Password managers matter for 3.3.8 Accessible Authentication too. Both are covered in WCAG 2.2: What the Standard Actually Asks.
<form action="/login" method="post">
<label for="login-email">Email</label>
<input id="login-email" name="email" type="email" autocomplete="username webauthn">
<label for="login-password">Password</label>
<input id="login-password" name="password" type="password" autocomplete="current-password">
<button type="submit">Log in</button>
</form>Match each field to the autocomplete token it should use.
inputmode and enterkeyhint for mobile keyboards
On a phone, the keyboard is half the form. type already picks a keyboard for email, phone and URL fields. Two more attributes give you finer control without changing what the field accepts.
inputmode picks the on-screen keyboard: numeric (digits only), decimal (digits and a decimal point), tel, email, url, search, text or none. It does not validate anything. It only changes which keys appear.
That makes it the right tool for numbers that are really codes. type="number" is designed for quantities you might count up and down: it shows a spinner, the mouse wheel can change the value while the field has focus, it accepts e because 1e5 is a valid number, and very long digit strings are not what it is for. A card number, a postcode, an account number or a one-time code is text that happens to contain digits:
<label for="code">Security code</label>
<input id="code" name="code" type="text" inputmode="numeric"
pattern="[0-9]{6}" autocomplete="one-time-code" spellcheck="false">A simple test: if adding one to the value makes sense ("3 tickets" becomes "4 tickets"), use type="number". If it does not (a card number plus one is nonsense), use type="text" with inputmode="numeric".
enterkeyhint changes the label on the Enter key: enter, done, go, next, previous, search or send. Use next on the early fields of a step and done or send on the last one, so people know what pressing it will do. Like inputmode, it only changes the label. If you show "next", make sure Enter really does what people expect. Both attributes are Baseline Widely available.
Grouping with fieldset and legend
In the example above, the radio buttons sit inside a fieldset with a legend. A fieldset groups related controls, and its legend is the caption for the whole group. This matters most for radios and checkboxes: each button has its own label ("Set menu"), but the question they answer ("Menu") lives in the legend. A screen reader announces both, so the learner hears "Menu, Set menu, radio button, 1 of 2".
Buttons
A button inside a form has a type, and the default is submit. That surprises people: a button meant to open a help panel will submit the form if you forget the type.
type="submit"sends the form. Pressing Enter in a text field does the same.type="reset"puts every field back to its starting value. It is rarely useful and easy to click by mistake.type="button"does nothing on its own. Use it for buttons that JavaScript controls.
Always write the type explicitly. Future you will thank you.
Match each need to the element or type that fits.
Built-in validation
Before a form is sent, the browser checks each field against the rules you wrote in HTML. If something fails, it stops the submission, focuses the first bad field and shows a message. No JavaScript needed.
| Attribute | Rule |
|---|---|
required | The field cannot be empty |
min, max | Lowest and highest allowed number or date |
minlength, maxlength | Shortest and longest text |
pattern | The text must match a regular expression |
type="email", type="url" | The text must look like an email or web address |
CSS can see the result too, through the :invalid and :valid pseudo-classes. The live preview on this page blocks real form submissions for safety, so the example below shows validity with colour instead of the browser's pop-up message.
Preview
Type sam into the username and the border turns green. Type Sam (capital S) and it turns red, because the pattern only allows lowercase. Now change the pattern to [A-Za-z]{3,12} and try again. Put 9 in the age field, then change min="13" to min="5".
input type='number' name='qty' min='1' max='10' and someone types 12. What happens when they press the submit button?:user-invalid versus :invalid
Try the demo above again and notice something: the fields were red before you typed anything. An empty required field is invalid from the moment the page loads, so :invalid matches it straight away. Shouting at people before they have started is bad design, and it is the reason many teams gave up on CSS validation styles and wrote JavaScript instead.
:user-invalid fixes that. It matches an invalid field only after the user has interacted with it: they changed the value and left the field, or they tried to submit the form. :user-valid is its partner. Both are Baseline Widely available, so you can use them without a fallback.
Preview
Type sam into the second field, then click somewhere else on the page: it turns red only now. Fix it to sam@example.com and it turns green. Then change .polite:user-invalid to .polite:invalid and see the eager behaviour come back.
Accessible error messages
A red border tells a sighted person that something is wrong, but not what, and it tells a screen reader user nothing at all. Three WCAG criteria describe what a good error does:
- 1.4.1 Use of Color (A): colour cannot be the only signal. Add text, and ideally an icon.
- 3.3.1 Error Identification (A): the field in error is identified and the problem is described in text.
- 3.3.3 Error Suggestion (AA): if you know how to fix it, say so. "Enter an email address like name@example.com" beats "Invalid input".
In markup, an error message is a normal element next to the field, linked to it so assistive technology reads it with the field:
<label for="email">Email</label>
<input id="email" name="email" type="email" required
aria-invalid="true" aria-describedby="email-error">
<p id="email-error" class="error">Error: enter an email address like name@example.com</p>aria-describedbypoints at the message'sid. When the field gets focus, a screen reader reads the label, then the role, then the description: "Email, edit text, invalid entry, Error: enter an email address like name@example.com". It can list several ids, so a hint and an error can both be attached.aria-invalid="true"marks the field as being in error. Set it only after you have checked the field, and remove it when the error is fixed. Never put it on every field on page load.- The word "Error:" in the text helps people who cannot see the red styling and people using Windows forced colours, where your colours are replaced.
You may also see aria-errormessage, an attribute made for exactly this job. Screen reader support has been patchy for years, so aria-describedby remains the dependable choice. Check current support before switching.
The error summary
On a long form, an error on field nine is easy to miss. The pattern used by GOV.UK and most large public services adds an error summary when submission fails: a box at the top titled "There is a problem", listing every error as a link that jumps to its field. Focus moves to the summary, so screen reader users hear it straight away, and each link takes keyboard users to the right field. Many teams also prefix the page title with "Error:" so the problem is announced in the browser tab too.
To control the messages yourself, add novalidate to the form. That turns off the browser's pop-up bubbles but keeps every rule: you still read the result from the Constraint Validation API, where input.validity.valueMissing, typeMismatch, patternMismatch and friends tell you exactly which rule failed.
Preview
Press Create account with both fields empty. The summary appears and takes focus, and each field gets its own message. Click a link in the summary and focus jumps to that field. Type sam as the email and submit again to get the more specific message. Then delete the novalidate attribute and see the browser's own bubble take over instead.
When to check matters as much as how. Validate on submit, and after that on blur for fields that already showed an error, so the message clears once fixed. Do not validate on every keystroke: an email field that turns red after the first letter is just noise, and a screen reader that announces each change is worse. If you need moving focus or live announcements beyond this, Keyboard Support and Focus Management and the live regions section of ARIA Widget Patterns go deeper.
Sending the data: GET vs POST
When a valid form is submitted, the browser collects every named field into pairs like name=value and sends them to the action address.
- GET puts the pairs in the address bar:
/search?q=pasta&page=2. That makes the result easy to bookmark and share, so it suits searches and filters. It is the default method. Never use it for passwords or private data, because addresses end up in history and server logs. - POST sends the pairs in the body of the request, out of sight. Use it when the form changes something: creating an account, placing an order, posting a comment.
A simple rule: if submitting twice would be harmless (a search), use GET. If it would do something twice (charge a card), use POST. In Forms in JavaScript, part of the JavaScript & TypeScript course, you will handle submissions with JavaScript so the page does not reload.
Put the steps of a form submission in order.
- Tap the steps below in the right order.
The submit button starts the process.
Multi-step forms and redundant entry
Checkouts, insurance quotes and job applications usually span several steps. WCAG 2.2 added criterion 3.3.7 Redundant Entry (level A) for them: information the user already gave in the same process must be filled in for them or offered as a choice, not typed again. The classic case is the billing address after the shipping address.
<fieldset>
<legend>Billing address</legend>
<label>
<input type="checkbox" name="billing-same" checked> Same as delivery address
</label>
<!-- billing fields, with autocomplete="billing ...", shown only when unticked -->
</fieldset>Exceptions exist where re-entry is the point, such as confirming a new password or a security check, and WCAG 2.2: What the Standard Actually Asks lists them. A few habits make long forms bearable for everyone: say how many steps there are ("Step 2 of 4"), keep answers when people go back, ask only for what you need, and show a "check your answers" page before anything is charged.
- form
- An element that groups fields and sends their values to an address when submitted.
- label
- Visible text describing a field, linked to it with for and id or by wrapping it.
- name
- The key a field's value is sent under. Fields without a name are not submitted.
- fieldset and legend
- A group of related controls and the caption that describes the whole group.
- constraint validation
- The browser's built-in checks (required, pattern, min, max, type) that run before a form is sent.
- GET and POST
- Two ways to send form data: in the address (GET, for searches) or in the request body (POST, for changes).
- autocomplete token
- A standard value such as email, new-password or postal-code that tells the browser and password managers what a field is for.
- inputmode
- An attribute that picks the on-screen keyboard (numeric, decimal, email and so on) without changing what the field accepts.
- :user-invalid
- A pseudo-class that matches an invalid field only after the user has interacted with it or tried to submit.
- aria-describedby
- Links a field to extra text, such as a hint or an error message, that assistive technology reads with it.
- error summary
- A box at the top of a failed form listing every error as a link to its field, which receives focus on submit.