When a user submits invalid form data, there are two things you need to do — and accessibly.

  1. Mark the field as invalid
  2. Associate an error message with the field

How it looks

image of inline error example

The code

aria-invalid

The accessible way to mark the invalid state of the input is to attribute it with aria-invalid="true". The "true" value is necessary: ARIA attributes do not work like HTML5 boolean attributes.

<label for="email">Email</label>
<input type="text" id="email" aria-invalid="true">
 

The visual representation of this state is manifested by the red cross icon. This can be achieved in CSS, using a background image, for example.

[aria-invalid="true"] {
background: url(path/to/cross.svg) no-repeat center right;
}
 

aria-describedby

The label is associated with the input by making the for and id attributes share a value. Similarly, aria-describedby should take the id of the error message element.

<label for="email">Email</label>
<input type="text" id="email" aria-invalid="true" aria-describedby="email-error">
<div id="email-error">Please make sure your email address is formatted correctly</div>
 

Now, when a screen reader user focuses the input, the label and invalid state will be announced, and the error message will be appended to that announcement.