On this page
  1. Accessible Forms & Validation
  2. Contents
  3. Connecting Labels, Hints & Errors
  4. Styling Validation States with CSS

Accessible Forms & Validation

Prev: Semantic Document Structure | Up: tutorials | Next: Media & Responsive Images
Rel: Forms & Inputs, Form & Validation Attributes, Pseudo-Classes, Forms, Validation & Fetch
Ref: MDN Web Docs — HTML Forms
Tags: #public #web #html #tutorials #forms


Contents


Connecting Labels, Hints & Errors

Bind <label> to its input via for/id, link helper or error text via aria-describedby, and use aria-invalid="true" when an error is shown.

<form method="post">
  <div>
    <label for="handle">Username</label>
    <input
      id="handle"
      name="handle"
      type="text"
      required
      minlength="4"
      pattern="[a-z0-9_]+"
      aria-describedby="handle-hint"
    />
    <p id="handle-hint">Use at least 4 lowercase letters, digits, or underscores.</p>
  </div>
  <button type="submit">Save Profile</button>
</form>

Styling Validation States with CSS

Prefer :user-valid and :user-invalid over :valid/:invalid so fields are not styled as errors before the user interacts with them:

input:user-invalid {
  border-color: #c62828;
}
input:user-valid {
  border-color: #2e7d32;
}

Linked from

Related notes