網頁設計實驗室

Web Design Laboratory

表單驗證 | 如何在HTML與CSS中配合JavaScript建立響應式表單驗證

Dec 17, 2024

↓程式碼演示在文章底部↓

建立表單驗證的步驟

建立一個 index.html 文件。檔案名稱必須是index,副檔名是.html
建立一個 thank-you.html 文件。檔案名稱必須是index,副檔名是.html
建立一個 style.css 文件。檔案名稱必須是 style 且副檔名為 .css
建立一個 script.js 文件。檔案名稱必須是 script 且副檔名為 .js


將以下 HTML 程式碼新增至您的index.html檔案

此表單包括全名、電子郵件、密碼、出生日期和性別字段,但您可以根據需要新增或刪除字段。

 
        <!DOCTYPE html>
          
          <html lang="en">
          <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Form Validation in HTML | CodingNepal
          <link rel="stylesheet" href="style.css">
              
              <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
              </head>
              <body>
              <form action="thank-you.html">
              <h2>Form Validation
              <div class="form-group fullname">
              <label for="fullname">Full Name
              <input type="text" id="fullname" placeholder="Enter your full name">
              </div>
              <div class="form-group email">
              <label for="email">Email Address
              <input type="text" id="email" placeholder="Enter your email address">
              </div>
              <div class="form-group password">
              <label for="password">Password
              <input type="password" id="password" placeholder="Enter your password">
              <i id="pass-toggle-btn" class="fa-solid fa-eye">
              </div>
              <div class="form-group date">
              <label for="date">Birth Date
              <input type="date" id="date" placeholder="Select your date">
              </div>
              <div class="form-group gender">
              <label for="gender">Gender
              <select id="gender">
              <option value="" selected disabled>Select your gender
              <option value="Male">Male
              <option value="Female">Female
              <option value="Other">Other
              </select>
              </div>
              <div class="form-group submit-btn">
              <input type="submit" value="Submit">
              </div>
              </form>
              <script src="script.js">
              </body>
              </html>

將以下 HTML 程式碼新增至您的thank-you.html檔案

使用者使用有效資料填寫表單時,他們將被重新導向至此 HTML 頁面

 
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Thanks page
        </head>
        <body>
        <h1>Thank you for filling out the form correctly.
        </body>
        </html>


將以下 CSS 程式碼新增至您的檔案 style.css以設定登入表單的樣式

                   @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600;700&display=swap');
                  * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                    font-family: 'Open Sans', sans-serif;
                  }
                  body {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 0 10px;
                    min-height: 100vh;
                    background: #1BB295;
                  }
                  form {
                    padding: 25px;
                    background: #fff;
                    max-width: 500px;
                    width: 100%;
                    border-radius: 7px;
                    box-shadow: 0 10px 15px rgba(0, 0, 0, 0.05);
                  }
                  form h2 {
                    font-size: 27px;
                    text-align: center;
                    margin: 0px 0 30px;
                  }
                  form .form-group {
                    margin-bottom: 15px;
                    position: relative;
                  }
                  form label {
                    display: block;
                    font-size: 15px;
                    margin-bottom: 7px;
                  }
                  form input,
                  form select {
                    height: 45px;
                    padding: 10px;
                    width: 100%;
                    font-size: 15px;
                    outline: none;
                    background: #fff;
                    border-radius: 3px;
                    border: 1px solid #bfbfbf;
                  }
                  form input:focus,
                  form select:focus {
                    border-color: #9a9a9a;
                  }
                  form input.error,
                  form select.error {
                    border-color: #f91919;
                    background: #f9f0f1;
                  }
                  form small {
                    font-size: 14px;
                    margin-top: 5px;
                    display: block;
                    color: #f91919;
                  }
                  form .password i {
                    position: absolute;
                    right: 0px;
                    height: 45px;
                    top: 28px;
                    font-size: 13px;
                    line-height: 45px;
                    width: 45px;
                    cursor: pointer;
                    color: #939393;
                    text-align: center;
                  }
                  .submit-btn {
                    margin-top: 30px;
                  }
                  .submit-btn input {
                    color: white;
                    border: none;
                    height: auto;
                    font-size: 16px;
                    padding: 13px 0;
                    border-radius: 5px;
                    cursor: pointer;
                    font-weight: 500;
                    text-align: center;
                    background: #1BB295;
                    transition: 0.2s ease;
                  }
                  .submit-btn input:hover {
                    background: #179b81;
                  }


將以下 JavaScript 程式碼新增至您的檔案script.js以啟用表單驗證

                         // Selecting form and input elements
      const form = document.querySelector("form");
      const passwordInput = document.getElementById("password");
      const passToggleBtn = document.getElementById("pass-toggle-btn");
      // Function to display error messages
      const showError = (field, errorText) => {
          field.classList.add("error");
          const errorElement = document.createElement("small");
          errorElement.classList.add("error-text");
          errorElement.innerText = errorText;
          field.closest(".form-group").appendChild(errorElement);
      }
      // Function to handle form submission
      const handleFormData = (e) => {
          e.preventDefault();
          // Retrieving input elements
          const fullnameInput = document.getElementById("fullname");
          const emailInput = document.getElementById("email");
          const dateInput = document.getElementById("date");
          const genderInput = document.getElementById("gender");
          // Getting trimmed values from input fields
          const fullname = fullnameInput.value.trim();
          const email = emailInput.value.trim();
          const password = passwordInput.value.trim();
          const date = dateInput.value;
          const gender = genderInput.value;
          // Regular expression pattern for email validation
          const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
          // Clearing previous error messages
          document.querySelectorAll(".form-group .error").forEach(field => field.classList.remove("error"));
          document.querySelectorAll(".error-text").forEach(errorText => errorText.remove());
          // Performing validation checks
          if (fullname === "") {
              showError(fullnameInput, "Enter your full name");
          }
          if (!emailPattern.test(email)) {
              showError(emailInput, "Enter a valid email address");
          }
          if (password === "") {
              showError(passwordInput, "Enter your password");
          }
          if (date === "") {
              showError(dateInput, "Select your date of birth");
          }
          if (gender === "") {
              showError(genderInput, "Select your gender");
          }
          // Checking for any remaining errors before form submission
          const errorInputs = document.querySelectorAll(".form-group .error");
          if (errorInputs.length > 0) return;
          // Submitting the form
          form.submit();
      }
      // Toggling password visibility
      passToggleBtn.addEventListener('click', () => {
          passToggleBtn.className = passwordInput.type === "password" ? "fa-solid fa-eye-slash" : "fa-solid fa-eye";
          passwordInput.type = passwordInput.type === "password" ? "text" : "password";
      });
      // Handling form submission event
      form.addEventListener("submit", handleFormData);


我在這邊線上演示

See the Pen Untitled by 周平(瑪雅網路科技) (@vzhzchpn-the-vuer) on CodePen.


CodePen 官網: https://codepen.io/