CodeBlanks Logo Icon CodeBlanks

Form accessibility

HTML course · Intermediate · Lesson 55/67

Use label, aria-required and aria-invalid.

The label and for/id link

A form field gets its accessible name from a linked <label>. The link goes both ways: the label's for attribute and the input's id carry the same value. Example: <label for="email">Email</label> <input id="email">.

So when a screen reader focuses the input, it says 'Email'. Clicking the label also activates the input; that small touch grows the click area.

required and aria-invalid

For a normal <input>, use HTML's own required attribute to mark it as mandatory; this informs both the browser and screen readers. aria-required="true" is only for custom components built with <div>; it is redundant on standard inputs.

When you show a validation error, adding aria-invalid="true" lets screen-reader users hear the error. This carries no visual cue; it only informs assistive tech.

Exercise Write an accessible form field

Add a <form> to body. Inside the form put a <label for="email">Email</label> and an <input id="email" required>. The label's for value and the input's id must match exactly.

Show example solution
<body>
  <form>
    <label for="email">Email</label>
    <input id="email" required>
  </form>
</body>

Test yourself

  1. Which of these is wrong usage?

    • label for="name" with input id="name"
    • Putting input inside label
    • label for="name" with input name="name"
    • label for="surname" with input id="surname"
    Show answer

    label for="name" with input name="name" — Correct. for matches id, not name.

  2. Write the label tag

    <____ for="email">Email</label>
    <input id="email">
    Show answer
    <label for="email">Email</label>
    <input id="email">
  3. Match each attribute to its purpose

    for
    Links label to input
    id
    Input's unique key
    aria-required
    Marks a required field
    aria-invalid
    Marks a wrong value

All lessons in Intermediate