← 레벨 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 은 플렉스박스를 옆으로가 아니라 위아래로 쌓이게 해. 자식 요소들이 하나씩 아래에 줄 서.

보여줄게: 자바스크립트로 검사하기

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에서 방명록이 있는 진짜 서버를 만들고 이 폼을 연결할 거야. 그때부터 메시지가 진짜로 저장돼!

네 차례 💪

프로젝트에 맞는 폼을 사이트에 넣고, 입력 검사도 붙여.

⚠️

프로의 보안 습관: 사용자가 쓴 내용을 절대 믿지 마. 항상 검사해 – 빈 칸, 말도 안 되는 나이, 너무 긴 글. 오늘은 예의를 위해서지만, 진짜 앱에서는 공격에 대한 첫 방어선이야.

✅

직접 확인해: 빈 폼을 내면 칸이 빨간색이 되고 메시지가 떠. 채운 폼은 이름으로 고마워하고 칸을 비워. 친절하고, 상냥하고, 프로답게.

이 수업에서 가져갈 것