Thuta Learning
HTML
IntermediateWeb DevelopmentBeginner

Labels & Validation

HTMLLesson 2425 min

What you'll walk away with

  • Connect labels with for/id (or by wrapping) so you get both a click target and an accessible name
  • Predict which validity flag required, type, minlength, maxlength, pattern, min and max each trigger
  • Explain why an empty optional field is valid and why pattern must match the whole value
  • Tie a format hint to its field with aria-describedby while keeping server validation in place

Explain it simply

Explain it simply

An input without a label is like a switch with no sign on it: nobody knows what it does. A label shows text like "Email address" next to the field, tells screen readers the field's name, and moves focus to the field when clicked.

Validation is the doorkeeper. Add attributes such as required, minlength and pattern, and the browser checks the form before sending it, takes the user to the first problem field and explains what is wrong, without a single line of JavaScript.

Problem → Why → Solution

The problem: a for/id mismatch and a rule nobody explains

This form looks normal. But the label's for="e-mail" does not match the input's id="email", so clicking the label does nothing and a screen reader announces the field only as "edit text". The username field has a pattern, yet the rule is written nowhere, so the user just sees a generic "match the requested format" message and has no idea what to change.

signup.html
<form>
  <label for="e-mail">Email address</label>
  <input id="email" name="email" type="email" required>

  <label for="user">Username</label>
  <input id="user" name="username" pattern="[a-z0-9_]{3,16}" required>

  <button type="submit">Create account</button>
</form>

Why does this happen?

A label connects to its control only when the strings match exactly; to the browser "e-mail" and "email" are two unrelated ids. A pattern is a rule for the machine and explains nothing to a human, so every rule also needs a visible hint near the field, linked with aria-describedby.

Core concept: labels name controls, constraints let the browser check them

There are two ways to connect a label. Explicitly, the for of <label for="x"> matches the control's id="x". Implicitly, the control sits inside the label: <label>Email <input ...></label>. Either way you get two results: the label text becomes the control's accessible name, and clicking the label focuses the control (or toggles a checkbox). Every id must be unique on the page.

Each constraint attribute maps to a validity flag: required to valueMissing, type="email" to typeMismatch, minlength/maxlength to tooShort/tooLong, pattern to patternMismatch, and min/max to rangeUnderflow/rangeOverflow. On submit, the browser checks the fields, focuses the first invalid one and shows its message. From JavaScript you can read flags like input.validity.patternMismatch and call checkValidity() or reportValidity().

Remember three finer rules. First, an empty field that is not required skips pattern, minlength and type checks and counts as valid. Second, pattern must match the whole value: the browser anchors it with ^ and $ for you, so [0-9]{5} rejects 123456. Third, minlength is only checked on values the user typed, not on values a script set.

The text inside the error bubble is written by the browser in the browser's own language, so the wording differs between Chrome and Firefox. Adding a title attribute to a pattern field makes some browsers append that text to the message, but you cannot rely on it on touch screens or with screen readers. For a custom message, JavaScript offers setCustomValidity(); either way, the safest choice is to keep the rule visible on the page.

Browser validation gives users fast feedback; it is not protection. Attributes can be deleted in DevTools, so the server must enforce every rule again. And never show an error with a red border alone: some people cannot tell colours apart, so say it in words too.

Mental model: name it, constrain it, explain it
  1. Link a label with for/id
  2. Add constraint attributes
  3. Write the rule as a visible hint
  4. Browser checks on submit
  5. Server checks again

The browser can do the checking; explaining the rule is still your job.

General pattern

html
<label for="field-id">Label text</label>
<input id="field-id" name="field" type="kind"
       required minlength="N" pattern="regex"
       aria-describedby="field-hint">
<p id="field-hint">Explain the rule in plain words.</p>

<label><input name="flag" type="checkbox" required> Wrapped label</label>

for and id must be the identical string. Add only the constraints you need, and point aria-describedby at the hint paragraph's id. The last line shows the implicit style, with the control wrapped inside the label.

Example: an account form with email and password

Both fields here are correctly linked to labels, and three rules are handed to the browser. Press Create account with everything empty, then try a wrong email such as "abc".

html
<form>
  <label for="email">Email address</label>
  <input id="email" name="email" type="email" required>

  <label for="password">Password</label>
  <input id="password" name="password" type="password" minlength="8" required>

  <button type="submit">Create account</button>
</form>

Code breakdown

  1. Explicit label<label for="email">Email address</label>

    for="email" exactly matches the input's id="email", so the field's accessible name is "Email address" and clicking the label places the cursor there.

  2. Email constraints<input id="email" name="email" type="email" required>

    required flags an empty value as valueMissing, and type="email" flags "abc", which has no @, as typeMismatch.

  3. Password lengthtype="password" minlength="8" required

    A typed password shorter than 8 characters is tooShort. Without required an empty password would pass, which is why both attributes are needed.

  4. Submit button<button type="submit">Create account</button>

    Submitting is when the browser runs every constraint. If any field is invalid, no request is sent and focus moves to the first problem.

You should see
The "Email address" and "Password" labels, two boxes and a Create account button appear on one line. Submitting empty makes the browser focus the email field with a message such as "Please fill out this field" (wording varies by browser). A password under 8 characters is also blocked before submitting.

Linking hint and error text to a field

A label only provides the name. A longer instruction such as "lowercase letters, digits or _, 3 to 16 characters" has no native HTML attribute to attach it to the field, which makes this a genuine place for ARIA. aria-describedby points to the paragraph's id, and a screen reader reads the hint after the field's name. When the server returns an error, add the error text's id to aria-describedby and set aria-invalid="true".

username.html
<label for="username">Username</label>
<input id="username" name="username" pattern="[a-z0-9_]{3,16}" required
       aria-describedby="username-hint">
<p id="username-hint">3 to 16 characters: lowercase letters, digits or _.</p>

In real projects

Where this shows up in real projects

On sign-up and checkout forms, most teams keep native constraints as the foundation and use CSS's :user-invalid pseudo-class to show error styles only after the user has interacted with a field. Current major browsers support it, and unlike :invalid it does not paint every empty field red the moment the page loads. When a design system wants its own error messages, the form gets novalidate and JavaScript reads the validity API to write the text.

In accessibility audits, fields with no label and labels whose for does not match an id are among the most frequent findings. Automated checkers catch those, but whether an error message is understandable and appears next to its field still needs a person filling the form with a keyboard. On the backend, the same rules as the HTML, such as the username pattern, are enforced again and errors are returned per field.

Common mistakes

Common mistakes

1. Mismatched for/id, or duplicate ids

A one-character difference such as for="e-mail" versus id="email" breaks the link. When a component is used twice on a page and its ids repeat, both labels point at the first field. Check each field's name in the DevTools Accessibility pane.

2. Expecting pattern to match part of the value

pattern="[0-9]{5}" is not satisfied by a value that merely contains five digits; the whole value must be exactly five digits. You do not need to add ^ and $ yourself.

3. Showing errors only with colour or a placeholder

A red border alone says nothing to colour-blind or screen reader users, and a rule hidden in a placeholder vanishes as soon as typing starts. Write the rule and the error as text near the field and link them with aria-describedby.

Best practices

Best practices

  • Give every field a visible label, and mark optional fields with "(optional)" in the label.
  • Add a written hint to every field that has a format rule.
  • Repeat every HTML rule in the server code as well.

Mini challenge

Mini challenge: an account form that explains its rules

Write a form with a username, an age, a password and a terms checkbox. The browser must enforce every rule, and the user must be able to read each one.

  • Username: required, pattern="[a-z0-9_]{3,16}" and a hint linked with aria-describedby
  • Age: number with min="13", max="120" and required
  • Password: minlength="10", required and a hint stating the length
  • A terms checkbox wrapped inside its label, with required
account.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Create your account</title>
</head>
<body>
  <form action="/accounts" method="post">
    <!-- TODO: username + hint paragraph, linked with aria-describedby -->
    <!-- TODO: age between 13 and 120 -->
    <!-- TODO: password of at least 10 characters + hint -->
    <!-- TODO: required terms checkbox wrapped in its label -->
    <button type="submit">Create account</button>
  </form>
</body>
</html>

Expected: "Aye Aye" (a space and capitals) as the username gives patternMismatch, and 12 as the age gives rangeUnderflow. With aye_aye, 25, a 10-character password and the box ticked, the form is valid.

Show hint

Give each hint paragraph a unique id and put that id in the input's aria-describedby. A required checkbox is valid only when ticked.

Show solution
account.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Create your account</title>
</head>
<body>
  <form action="/accounts" method="post">
    <p>
      <label for="username">Username</label>
      <input id="username" name="username" pattern="[a-z0-9_]{3,16}" required
             aria-describedby="username-hint">
    </p>
    <p id="username-hint">3 to 16 characters: lowercase letters, digits or _.</p>
    <p>
      <label for="age">Age</label>
      <input id="age" name="age" type="number" min="13" max="120" required>
    </p>
    <p>
      <label for="pw">Password</label>
      <input id="pw" name="password" type="password" minlength="10" required
             aria-describedby="pw-hint" autocomplete="new-password">
    </p>
    <p id="pw-hint">At least 10 characters.</p>
    <p>
      <label>
        <input name="terms" type="checkbox" value="accepted" required>
        I accept the terms of use
      </label>
    </p>
    <button type="submit">Create account</button>
  </form>
</body>
</html>

Quick quiz 1 / 3

A user types 123456 into <input name="zip" pattern="[0-9]{5}">. What happens?

Quick quiz 2 / 3

What is the result of <label for="mail">Email</label><input id="email" name="email">?

Quick quiz 3 / 3

<input type="email" name="backup" minlength="6"> has no required attribute and is left empty. What happens on submit?

What to remember

  • Connect labels with an exactly matching for/id or by wrapping, giving both an accessible name and a click target.
  • Each constraint attribute sets a validity flag, and the browser checks them all on submit.
  • An empty optional field is valid, and pattern has to match the entire value.
  • Write rules as visible hints linked with aria-describedby, and always validate again on the server.

HTML Living Standard — Forms — WHATWG

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Labels & Validation | Thuta Learning