iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
Modern Web

Modern Web:從基礎、框架到前端學習系列 第 16

Day16:表單驗證與即時錯誤訊息

  • 分享至 

  • xImage
  •  

學習目標

  1. 了解表單驗證的基本概念。
  2. 學會使用**正規表達式 (RegEx)**驗證輸入格式。
  3. 學會輸入錯誤時即時顯示錯誤訊息。
  4. 做一個小型登入表單 (含即時驗證)

理論講解

1. 表單驗證類型

  • 必填欄位驗證:是否有輸入。
  • 格式驗證:例如 Email、密碼強度。
  • 長度驗證:最短/最長字元數。

2. 常見 RegEx (正規表達式)

Email 驗證: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
密碼至少 6 碼且包含數字: /^(?=.*[0-9]).{6,}$/

3. 即時驗證流程

  1. 監聽輸入框的inputblur事件。
  2. 驗證輸入值是否符合規則。
  3. 顯示錯誤訊息(紅字),否則顯示成功提示(綠字)。

實作練習:登入表單驗證

檔名:day16_form_validation.html

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Day16 - 表單驗證</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    form {
      width: 300px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    input {
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
    .error {
      color: red;
      font-size: 14px;
    }
    .success {
      color: green;
      font-size: 14px;
    }
    button {
      padding: 8px;
      background: darkblue;
      color: white;
      border: none;
      cursor: pointer;
    }
    button:disabled {
      background: gray;
    }
  </style>
</head>
<body>
  <h1>登入表單</h1>
  <form id="loginForm">
    <label>Email:</label>
    <input type="text" id="email" placeholder="請輸入 Email">
    <span id="emailError" class="error"></span>

    <label>密碼:</label>
    <input type="password" id="password" placeholder="請輸入密碼">
    <span id="passwordError" class="error"></span>

    <button type="submit" disabled>登入</button>
  </form>

  <script>
    const emailInput = document.getElementById("email");
    const passwordInput = document.getElementById("password");
    const emailError = document.getElementById("emailError");
    const passwordError = document.getElementById("passwordError");
    const loginForm = document.getElementById("loginForm");
    const submitBtn = loginForm.querySelector("button");

    // 驗證函式
    function validateEmail(email) {
      const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return regex.test(email);
    }

    function validatePassword(password) {
      const regex = /^(?=.*[0-9]).{6,}$/; // 至少6碼,包含數字
      return regex.test(password);
    }

    // 即時驗證
    emailInput.addEventListener("input", () => {
      if (!validateEmail(emailInput.value)) {
        emailError.textContent = "請輸入正確的 Email 格式";
      } else {
        emailError.textContent = "";
      }
      checkForm();
    });

    passwordInput.addEventListener("input", () => {
      if (!validatePassword(passwordInput.value)) {
        passwordError.textContent = "密碼需至少 6 碼,且包含數字";
      } else {
        passwordError.textContent = "";
      }
      checkForm();
    });

    // 確認表單是否可提交
    function checkForm() {
      if (validateEmail(emailInput.value) && validatePassword(passwordInput.value)) {
        submitBtn.disabled = false;
      } else {
        submitBtn.disabled = true;
      }
    }

    // 表單送出事件
    loginForm.addEventListener("submit", (event) => {
      event.preventDefault(); // 阻止預設送出
      alert("登入成功!");
    });
  </script>
</body>
</html>

✅ 今日作業

  1. 把上面的程式碼跑起來,試著輸入不同格式的 Email 和密碼,看錯誤訊息是否即時顯示。
  2. 修改程式碼,新增一個確認密碼欄位,並驗證「兩次密碼是否一致」。

上一篇
Day15:JavaScript 事件處理 (Event Handling) 進階
下一篇
Day17:JSON 與資料格式處理
系列文
Modern Web:從基礎、框架到前端學習20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言