Start learning free

LESSON 40 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Say What Is Wrong in JavaScript

Practice

A form should check what the visitor typed before it uses it, and say clearly what is wrong. The message goes right under the field, and it goes away as soon as the field is fixed.

Two attributes make the message reach every visitor. role="alert" on the message makes screen readers read it out the moment it appears. aria-invalid="true" on the field tells them the field is wrong. The check prints them as alert: … and (invalid).

In JavaScript, the hidden attribute is a property you set to true or false; setAttribute and removeAttribute change any other attribute. trim() drops the spaces at both ends of a string. For a promo code field:

const promo = document.querySelector("#promo");
console.log("  SAVE ".trim().length);   // 4
promo.setAttribute("aria-invalid", "true");
promo.removeAttribute("aria-invalid");

The newsletter form now has a Name field. The check types "A" as the name and an address, clicks Subscribe, then fixes the name:

> click "Subscribe"
    field "Name": "A" (invalid)
    alert: Your name needs at least 2 letters
    field "Email": "ana@example.com" (email)
> type "n" into "Name"
    field "Name": "An"
    field "Email": "ana@example.com" (email)
> click "Subscribe"
    field "Name": "An"
    field "Email": "" (email)
    text: Thanks, ana@example.com

Your task: in the submit listener, when the trimmed name is shorter than 2 characters, show #name-error, set aria-invalid on the field and stop before the thanks. Then add an input listener on the Name field that hides the message and removes aria-invalid once the name has 2 characters.


Assignment
Follow the Coding Tutorial to check the Name field in the newsletter's submit listener, and to clear the error while the visitor types.


Hint
return inside the if ends the listener, so the thanks lines below it don't run. The input listener uses the same test as the submit listener.


STEP 1 OF 10
    Ctrl + Enter to check

    Dom Form Errors in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free