Bài học hiện đang bằng tiếng Séc. Giao diện đã được dịch – nội dung bài học sẽ sớm có.

← Cấp 2 – Pháp sư

Bài 7 / 8 ⏱ 30 phút

Form bắt lỗi nhập liệu

Khách để lại tin nhắn, và form lịch sự chỉ ra khi thiếu gì đó.

Xem này: form trong HTML

Form là tập các ô khách gõ vào:

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

Và chút CSS cho đẹp:

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 xoay flexbox từ ngang sang dọc: con xếp từng hàng.

Xem này: kiểm tra bằng 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
});

Thứ mới:

💡

Tin nhắn đi đâu? Chưa đi đâu cả – chưa có server nhận. Ta chỉ kiểm tra và cảm ơn. Nhưng nhớ chỗ này: ở Cấp 3, ta sẽ làm server thật với sổ lưu bút và nối form này. Lúc đó tin nhắn mới được lưu!

Đến lượt bạn 💪

Thêm form hợp dự án, có kiểm tra nhập liệu:

⚠️

Thói quen bảo mật của pro: không bao giờ tin những gì người dùng gõ. Luôn kiểm tra – ô trống, tuổi vô lý, chữ quá dài. Hôm nay làm cho lịch sự; trong app thật, đó là tuyến phòng thủ đầu tiên.

Tự kiểm tra: Gửi form trống tô đỏ ô và hiện thông báo. Form đầy đủ cảm ơn bằng tên và tự xóa. Lịch sự, thân thiện, chuyên nghiệp.

Điều cần nhớ từ bài học này