DevConnectDevConnect
Sign up · Log in

Forms, validation and error messages

Labels, when to validate, and how to write a message that helps.

15 min read

Forms are where most user frustration on the web is produced, and almost all of it comes from a short list of decisions.

Every field needs a label element. A <label for="email"> connected to the input is announced by screen readers and enlarges the click target, because clicking the label focuses the field. Placeholder text is not a label: it disappears as soon as typing begins, so the user loses the name of the field precisely when they are filling it in.

Input types do work for you. type="email", type="tel" and type="url" change the on-screen keyboard on a phone, which is the difference between an easy form and an unpleasant one. autocomplete="email" or autocomplete="name" lets the browser fill fields the user has typed a hundred times before.

Validate at the right moment. Validating on every keystroke marks a field invalid while the user is still typing the first character. Validating only on submit hides problems until the end. The usual answer is to validate a field when it loses focus, and from then on to update it as the user types, so a corrected field turns valid immediately.

Write the message for the person reading it. "Invalid input" says nothing. State what is wrong and what would be right: "Enter a date in the past", "This email address is already registered. Sign in instead". Put the message next to the field, connect it with aria-describedby, and mark the field aria-invalid.

Submission is a state too. Disable the submit button while the request is in flight so a double click does not create two records, and say what is happening. When it fails, say whether the data was saved. A form that clears itself after a failed submission destroys work the user cannot get back.

Go deeper

Lessons are not assessed. Progress towards the certificate is recorded from the work you submit. See all requirements