BPOW: Including error messages in labels

By October 16th, 2013

In this week's Best Practice of the Week (BPOW), we show you an easy trick for making sure that all users are notified when form data contains errors.

Forms are a huge part of our daily interactions on the web. However, sometimes we overlook one important part of that interaction when it comes to accessibility: error handling and messaging. Many times, error messages are visually displayed close to the field which has an error. However, screen reader users can’t benefit from these error messages if they are not programmatically linked to the corresponding form field. For example:


<p>
     <label for="first_name">First name</label>
     <input type="text" name="first_name" id="first_name">
     <span class="error">Please enter your first name</span>
</p>

In this case, the error message is indeed present, but it actually comes after the field with the error in the source order of the document. As mentioned previously, without a programmatic connection to the errroed field, screen reader users may not be able to tell which field has the error that they need to correct.

A relatively simple fix goes a long way to making sure that all users can understand which form fields have errors:


<p>
     <label for="first_name">
          First name
          <span class="error">Please enter your first name</span>
     </label>
     <input type="text" name="first_name" id="first_name">
</p>

Placing the error message directly inside the label for the field ensures that the error message will be automatically read out loud by assistive technology. We can also take this one step further by adding an icon with alternate text explicitly identifying the field as having an error:


<p>
     <label for="first_name">
          <img src="/images/error-icon.png" alt="Error:"> 
          First name
          <span class="error">Please enter your first name</span>
     </label>
     <input type="text" name="first_name" id="first_name">
</p>

For visual styling purposes, CSS can also be used to place the error message visually below the form field on the page.

Sometimes, providing an accessible user experience just comes down to considering everyone’s needs and making simple changes to the way that we present information.

Tagged with: