×

javascript · level 2 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

checks every answer before your code trusts it.

People leave boxes empty, type only spaces or spell things oddly. Validation means checking every answer before you use it, and kindly telling the person what to fix.

A keeps it tidy. Put an if near the top of the listener. If an answer is wrong, show a message and return. The listener stops there, so the code below only ever sees good answers.

Show the message by setting hidden = false on a ready-made element, and hide it again when all is well.

<form id="join">
  <input id="username" placeholder="Pick a username">
  <button>Join</button>
</form>
<p id="problem" hidden>Usernames need at least 3 letters.</p>
<p id="welcome"></p>
const username = document.querySelector("#username");
const problem = document.querySelector("#problem");
document.querySelector("#join").addEventListener("submit", (event) => {
  event.preventDefault();
  const picked = username.value.trim();
  if (picked.length < 3) { problem.hidden = false; return; }
  problem.hidden = true;
  document.querySelector("#welcome").textContent = `Welcome, ${picked}!`;
});

Press run it to bring the page to life.

console

nothing logged yet

Strings have .includes() too, like arrays: "sam@example.com".includes("@") is true.