← Level 2 – Wizard

Lesson 7 of 8 ⏱ 30 minutes

A form that catches mistakes

A visitor leaves you a message, and the form politely points out when something's missing.

Show me: a form in HTML

A form is a set of fields the visitor types into:

<form id="message-form">
  <label for="name">Your name</label>
  <input id="name" type="text" placeholder="Jake">

  <label for="message">Message</label>
  <textarea id="message" placeholder="Hi! You have an awesome website."></textarea>

  <button type="submit">Send message</button>
</form>

<p id="confirmation"></p>

And a bit of CSS to make it look nice:

form {
  display: flex;
  flex-direction: column;   /* fields stacked vertically */
  gap: 8px;
  max-width: 400px;
}

input, textarea {
  font: inherit;
  padding: 10px;
  border: 1px solid #d6d3d1;
  border-radius: 8px;
}

.error {
  border-color: #dc2626 !important;
  background-color: #fee2e2;
}

flex-direction: column turns flexbox from sideways to upright: children line up one below the other.

Show me: checking it in JavaScript

const form = document.getElementById("message-form");
const name = document.getElementById("name");
const message = document.getElementById("message");
const confirmation = document.getElementById("confirmation");

form.addEventListener("submit", (event) => {
  event.preventDefault();   // stop the normal submit (the page would reload)

  // Clear old error marks
  name.classList.remove("error");
  message.classList.remove("error");

  // Check that fields are filled in
  if (name.value.trim() === "") {
    name.classList.add("error");
    confirmation.textContent = "You forgot your name. 🙂";
    return;
  }

  if (message.value.trim() === "") {
    message.classList.add("error");
    confirmation.textContent = "So what do you want to tell me? Write something.";
    return;
  }

  // Everything's fine
  confirmation.textContent = "Thanks for the message, " + name.value + "! 💌";
  form.reset();   // empty the fields
});

New stuff:

💡

Where does the message go? Nowhere yet – we don’t have a server to receive it. We just check the message and say thanks. But remember this spot: in Level 3, we’ll build a real server with a guestbook and connect this form to it. Then messages will actually get saved!

Your turn 💪

Add a form to your website that makes sense for your project, with input checking:

⚠️

A security habit of the pros: never trust what a user types. Always check it – an empty field, a nonsensical age, text that’s too long. Today you do it for politeness; in real applications, it’s the first line of defense against attackers.

Check yourself: Submitting an empty form marks the field red and shows a message. A filled-in form says thanks by name and clears itself. Polite, friendly, professional.

What to take away from this lesson