Accessible form structure

Write accessible error messages

Identify the field, explain the problem, preserve entered values, and make errors available without relying only on color.

8 minute lesson

~~~

A useful error identifies the field, explains the problem, and tells the person how to fix it.

“Email is invalid” is vague. “Enter an email address in the format [email protected]” is actionable.

Place the message next to the field and connect it:

<label for="email">Email address</label>
<input
  id="email"
  name="email"
  type="email"
  value="ada@"
  aria-invalid="true"
  aria-describedby="email-error"
>
<p id="email-error">Enter an email address in the format [email protected].</p>

aria-invalid marks the current state. aria-describedby connects the explanation. The visible text means the error does not depend on a red border or icon.

When several fields fail, add a summary near the top:

<div role="alert" tabindex="-1">
  <h2>There are 2 problems</h2>
  <a href="#email">Enter a complete email address</a>
</div>

Preserve valid values when returning the form. Re-entering unrelated information is a punishment, not validation.

Do not echo sensitive values such as passwords. Escape submitted text before rendering it into HTML.

Try errors with color disabled, at 200% zoom, and with a screen reader if available. You should still be able to find the problem and its field.

Lesson completed