Mark Invalid Fields Accessibly

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

A delivery form has text inputs labelled "Full name" and "Postcode" and a "Save" button. Both are required. When Save is pressed, each field that's empty (or only spaces) gets aria-invalid="true" and an error message next to it (outside the label), linked to the input with aria-describedby: "Enter your full name" or "Enter your postcode". Filled-in fields must not be marked invalid (no aria-invalid, or "false") and have no error. The fields are checked again on every Save, and when both are filled in, "Saved" appears below the form. Nothing is marked before the first Save. Give the form noValidate, so the browser's own checks never get in the way.

Your code must pass

  • Nothing is marked invalid at first
  • Save marks only the empty field invalid
  • Each error is linked with aria-describedby
  • Spaces alone don't count as filled in
  • Fixing a field and saving again clears its error