Skip to content

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.

20 min read0/7 questions

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:

  • action is the address the data is sent to. Leave it out and the form sends to the current page.
  • method is how it is sent: get or post (more on these at the end of the lesson).
  • Each field inside needs a name. The name is the key the server receives, like email=sam@example.com. A field without a name is 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.

HTML & CSS
<style> form { display: grid; gap: 12px; max-width: 320px; } label { font-weight: 600; } input { padding: 8px; font: inherit; border: 2px solid #999; border-radius: 6px; }</style><form> <label for="name">Your name</label> <input id="name" name="name"> <label for="email">Email</label> <input id="email" name="email" type="email" placeholder="you@example.com"> <label> <input type="checkbox" name="news"> Send me the newsletter </label></form>

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.

Quick check
A sign-up form uses placeholder='Email' on its input and has no label. What is the main problem?
Need a nudge? A hint rules out a wrong answer.

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.

TypeWhat it gives you
textThe default single-line box
emailEmail keyboard on phones, checks for an @ and a domain
passwordHides the characters as you type
numberNumeric keyboard, up and down arrows, works with min, max, step
dateA native date picker
checkboxAn on or off choice; several can be ticked
radioPick exactly one from a group that shares a name
rangeA slider between min and max
fileA button to choose files from the device

Not every multi-line or multiple-choice field is an input:

  • textarea is a multi-line text box with a closing tag. Use it for messages and comments.
  • select with option children is a drop-down list. Each option has a value that gets sent, and the text between the tags is what people see.
HTML & CSS
<style> form { display: grid; gap: 10px; max-width: 340px; } label { font-weight: 600; } input, select, textarea { font: inherit; padding: 6px; } fieldset { border: 2px solid #ccc; border-radius: 8px; }</style><form> <label for="guests">Guests</label> <input id="guests" name="guests" type="number" min="1" max="8" value="2"> <label for="day">Date</label> <input id="day" name="day" type="date"> <label for="table">Seating</label> <select id="table" name="table"> <option value="inside">Inside</option> <option value="terrace">Terrace</option> </select> <fieldset> <legend>Menu</legend> <label><input type="radio" name="menu" value="set" checked> Set menu</label> <label><input type="radio" name="menu" value="a-la-carte"> A la carte</label> </fieldset> <label for="notes">Allergies or notes</label> <textarea id="notes" name="notes" rows="3"></textarea></form>

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.

FieldToken
Full namename (or given-name and family-name for two fields)
Email on a sign-up or contact formemail
Login identifier (email or username)username
Password on a login formcurrent-password
Password on sign-up or "change password"new-password
SMS or app codeone-time-code
Phonetel
Address in one textareastreet-address
Address in separate linesaddress-line1, address-line2
Postcode or ZIPpostal-code
Card number, expiry, name on cardcc-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-password means "offer the saved one". new-password means "offer to generate a strong one and save it". A sign-up form marked current-password gets no generated password, and a login form marked new-password gets a pop-up offering a new password to someone who only wants to log in.
  • Prefixes separate two addresses. autocomplete="shipping postal-code" and autocomplete="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 the pairs0/5 matched

Match each field to the autocomplete token it should use.

Choose an item, then its match on the other side.

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.

Quick check
A checkout asks for a 16-digit card number. Which input is the best choice?
Need a nudge? A hint rules out a wrong answer.

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 the pairs0/5 matched

Match each need to the element or type that fits.

Choose an item, then its match on the other side.

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.

AttributeRule
requiredThe field cannot be empty
min, maxLowest and highest allowed number or date
minlength, maxlengthShortest and longest text
patternThe 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.

HTML & CSS
<style> form { display: grid; gap: 10px; max-width: 320px; } label { font-weight: 600; } input { font: inherit; padding: 8px; border: 3px solid #999; border-radius: 6px; } input:invalid { border-color: #c62828; } input:valid { border-color: #2e7d32; }</style><form> <label for="user">Username (3 to 12 letters)</label> <input id="user" name="user" required pattern="[a-z]{3,12}"> <label for="age">Age</label> <input id="age" name="age" type="number" min="13" max="120" required> <label for="mail">Email</label> <input id="mail" name="mail" type="email" required></form>

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".

Quick check
This form has a field input type='number' name='qty' min='1' max='10' and someone types 12. What happens when they press the submit button?
Need a nudge? A hint rules out a wrong answer.

: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.

HTML & CSS
<style> form { display: grid; gap: 6px; max-width: 320px; } label { font-weight: 600; margin-top: 8px; } input { font: inherit; padding: 8px; border: 3px solid #999; border-radius: 6px; } .eager:invalid { border-color: #c62828; } .polite:user-invalid { border-color: #c62828; } .polite:user-valid { border-color: #2e7d32; } .hint { color: #555; font-size: 14px; }</style><form> <label for="a">Email, styled with :invalid</label> <input id="a" class="eager" type="email" required> <span class="hint">Red before you have done anything.</span> <label for="b">Email, styled with :user-invalid</label> <input id="b" class="polite" type="email" required> <span class="hint">Grey until you type and leave the field.</span></form>

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-describedby points at the message's id. 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.

HTML & CSS
<style> form { display: grid; gap: 4px; max-width: 340px; } label { font-weight: 600; margin-top: 10px; } input { font: inherit; padding: 8px; border: 2px solid #777; border-radius: 6px; } input[aria-invalid="true"] { border: 3px solid #c62828; } .error { color: #b00020; margin: 0; font-weight: 600; } .summary { border: 4px solid #b00020; padding: 10px 14px; margin-bottom: 8px; } .summary h2 { margin: 0 0 6px; font-size: 18px; } .summary ul { margin: 0; padding-left: 20px; } .summary a { color: #b00020; } [hidden] { display: none; }</style><form id="signup" novalidate> <div id="summary" class="summary" tabindex="-1" hidden> <h2>There is a problem</h2> <ul id="summary-list"></ul> </div> <label for="full-name">Full name</label> <input id="full-name" name="name" autocomplete="name" required> <p id="full-name-error" class="error" hidden></p> <label for="email">Email</label> <input id="email" name="email" type="email" autocomplete="email" required> <p id="email-error" class="error" hidden></p> <button type="submit" style="margin-top: 12px">Create account</button></form><script> const messages = { "full-name": { valueMissing: "Enter your full name" }, email: { valueMissing: "Enter your email address", typeMismatch: "Enter an email address like name@example.com", }, }; const form = document.getElementById("signup"); const summary = document.getElementById("summary"); const list = document.getElementById("summary-list"); function check(input) { const error = document.getElementById(input.id + "-error"); const rules = messages[input.id]; const failed = Object.keys(rules).find((rule) => input.validity[rule]); if (failed) { error.textContent = "Error: " + rules[failed]; error.hidden = false; input.setAttribute("aria-invalid", "true"); input.setAttribute("aria-describedby", error.id); return rules[failed]; } error.hidden = true; input.removeAttribute("aria-invalid"); input.removeAttribute("aria-describedby"); return null; } form.addEventListener("submit", (event) => { event.preventDefault(); list.innerHTML = ""; for (const input of form.querySelectorAll("input")) { const message = check(input); if (!message) continue; const link = document.createElement("a"); link.href = "#" + input.id; link.textContent = message; link.addEventListener("click", (e) => { e.preventDefault(); input.focus(); }); const item = document.createElement("li"); item.append(link); list.append(item); } summary.hidden = list.children.length === 0; if (!summary.hidden) summary.focus(); else form.insertAdjacentHTML("beforeend", "<p>Account created (demo).</p>"); });</script>

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.

Quick check
A field shows a red border and the text 'Invalid' below it. A screen reader user tabs to the field and hears only 'Email, edit text'. What is the most important fix?
Need a nudge? A hint rules out a wrong answer.

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 it in order5 steps

Put the steps of a form submission in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
A newsletter sign-up, end to end
YouBrowserServerclick Subscribecheck required, typePOST /subscribe email=...validate again, savethank-you page

The submit button starts the process.

1/5

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.

Key terms
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.