Validate the input

INPUT · Slides

Switch to an error look

01 / 03

Words alone can be missed

The error message is there, but on a small screen it might go unnoticed. Making the text box itself turn red is much harder to miss.

Changing the look means adding and removing a class. Instead of replacing everything with className, you learn the safer way: add one, remove one.

02 / 03

classList.add puts a class on

classList is the list of classes the element currently has. .add("is-invalid") puts is-invalid on the list.

Anything already there stays. You are adding one on top, which is why it is safe.

input.classList.add("is-invalid")// <input class="is-invalid">

03 / 03

classList.remove takes it off

When the error is fixed, take it off. .remove("is-invalid") drops only that class.

Other classes are untouched. Add and remove as a pair is the classList basics.

input.classList.remove("is-invalid")// <input> — back to normal