← 第 2 关 – 魔法师

第 7/8 课 ⏱ 30 分钟

会抓错误的表单

访客给你留言,表单会礼貌地指出缺了什么。

跟我看:HTML 里的表单

表单是访客输入的一组字段:

<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>

一点 CSS 让它好看:

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 把 flexbox 从横向变成纵向:子元素上下排列。

跟我看: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
});

新东西:

💡

留言去哪了? 现在还到不了任何地方——我们没有服务器接收。我们只检查并说谢谢。但记住这里:第 3 级我们会建真正的服务器和留言板,把这个表单连上去。那时留言真的会保存!

轮到你了 💪

给网站加一个符合项目的表单,带输入检查:

⚠️

专业人士的安全习惯: 永远不要信任用户输入的内容。总要检查——空字段、荒谬的年龄、太长的文字。今天是为了礼貌;在真实应用里,这是防攻击的第一道防线。

检查一下: 提交空表单会把字段标红并显示消息。填好的表单会按名字说谢谢并清空。礼貌、友好、专业。

这堂课你要记住