JavaScript >> Javascript 文檔 >  >> JavaScript

使用 Vanilla JavaScript 的客戶端表單驗證

簡介

現在的大多數網絡應用程序都需要您在某個時候填寫表格,無論是網上銀行應用程序還是音樂流媒體服務。

而且由於最終用戶永遠不會被信任,我們需要對我們的應用程序進行防呆,以便它檢測到輸入何時不正確,並通過適當的(錯誤)消息將其返回給用戶。

表單驗證 是一種用於防止用戶提供不符合應用程序要求的數據的技術。例如,確保提供的密碼至少包含一個大寫字符和一個數字。您可以在服務器端或客戶端驗證數據。

服務器端驗證 是在將用戶數據發送到服務器後驗證用戶數據的想法。如果數據不是預期的格式,則將其發送回給用戶。

另一方面,客戶端驗證 需要在將數據發送到服務器之前驗證用戶在瀏覽器中輸入的數據。這通常比服務器端驗證更有效,因為它可以防止從客戶端到服務器再返回。它也是一個早期的過濾器,它確保正確的數據通過,而不是一旦通過就處理錯誤的數據。

這並不意味著服務器不應該進行數據驗證——我們現在只是初步篩選。

在本教程中,我們將討論如何使用 vanilla JavaScript 在瀏覽器中驗證數據。

創建表單

讓我們製作一個簡單的註冊表單,它將包含以下字段:

  1. username
  2. first-password - 用於檢查某些條件的初始密碼
  3. second-password - 用作確認,並確保用戶沒有在 first-password 中打錯字 字段。

...並將其放入我們的 index.html 文件:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <script defer src="validate.js"></script>

    <title>Form Validation</title>
  </head>
  <body>
    <h1>Form Validation Using JavaScript</h1>

    <form id="form" action="/" method="GET">
      <!-- We are only interested in client-side validation now -->

      <!-- All the fields are required -->
      <div>
        <label for="username">Username: </label>
        <input type="text" name="username" id="username" autofocus required />
      </div>

      <div>
        <label for="first-password">Password: </label>
        <input
          type="password"
          name="firstPassword"
          id="first-password"
          required
        />
      </div>

      <div>
        <label for="second-password">Confirm Password: </label>
        <input
          type="password"
          name="secondPassword"
          id="second-password"
          required
        />
      </div>

      <button type="submit">Submit</button>
    </form>

    <div id="show-error">No validation error yet!</div>
    <!--We will use this div to display validation error -->
  </body>
</html>

這個 HTML 文件將呈現一個簡單的表單,如下所示:

表單要求

在編寫任何代碼之前,讓我們先回顧一下我們需要的驗證列表:

  • 確保用戶名以大寫字母開頭
  • 用戶名必須包含至少一位數字
  • 確保密碼長度在 8 到 20 個字符之間
  • 確保密碼至少包含一個大寫字母
  • 確認兩個密碼匹配

如果用戶輸入不符合上述要求,我們希望:

  • 最後一個div的文字 改變
  • 阻止表單提交

設置

首先,我們製作一個腳本文件validate.js 並將其與我們的 index.html 鏈接 head 中的文件 標籤:

<script defer src="validate.js"></script>

然後,讓我們從文檔中訪問相關字段:

// To disable the form from submitting
const form = document.querySelector('#form');
// To display the error message
const errorDiv = document.querySelector('#show-error');
// To validate the username
const username = document.querySelector('#username');
// To validate the password
const firstPassword = document.querySelector('#first-password');
// To confirm the password
const secondPassword = document.querySelector('#second-password'); 

為了簡單起見,讓我們讓表單驗證僅在單擊 submit 時運行 按鈕,而不是實時:

form.addEventListener('submit', (error) => {
 	// All validation checks are run in this method.   
}

實現驗證器

用戶名的首字母大寫

這很不言自明,如果字符串的第一個字母與其大寫變體相同,則表示 username 實際上以大寫字母開頭:

免費電子書:Git Essentials

查看我們的 Git 學習實踐指南,其中包含最佳實踐、行業認可的標準以及隨附的備忘單。停止谷歌搜索 Git 命令並真正學習 它!

// We will inlcude any and all errors in this string
let incorrectInput = '';

const firstLetter = username.value[0];

// Return true if first letter is uppercase
const firstLetterIsUpperCase = (firstLetter === firstLetter.toUpperCase()); 

if (!firstLetterIsUpperCase) {
    incorrectInput += ' The first letter of username must be uppercase.\n';
}

用戶名至少包含一位數

/\d/ 是一個匹配單個數字的正則表達式模式,這意味著如果它在提供的用戶名中匹配一次,則用戶名包含一個數字:

// Regex to see if a digit is in the username, returns true if there is
const usernameIncludesDigit = /\d/.test(username.value); 

if (!usernameIncludesDigit) {
    incorrectInput += 'Username must include at least one digit.\n';
}

密碼長度在 8 到 20 個字符之間

length string 屬性應該給我們密碼中的字符數。一個簡單的條件語句就可以解決問題:

const badPasswordLength = (firstPassword.value.length < 8 || firstPassword.value.length > 20);

if (badPasswordLength) {
    incorrectInput += ' The password should be within 8 to 20 characters.\n';
}

密碼至少包含一個大寫字符

這類似於我們為用戶名所做的。我們只需要修改正則表達式來檢查大寫字母而不是數字:

// Regex to see if a digit is in the username, returns true if there is
const passwordIncludesUppercase = /[a-z]/.test(firstPassword.value); 

if (!passwordIncludesUppercase) {
    incorrectInput += ' The password should contain at least one uppercase character.\n';
} 

驗證兩個密碼是否相同

最後,我們需要比較firstPasswordsecondPassword 看看他們是否匹配:

if (firstPassword.value !== secondPassword.value) {
    incorrectInput += 'The passwords do not match.\n';
}

顯示錯誤信息

在所有這些檢查之後,如果有任何條件不滿足,incorrectInput 不會是空字符串,並且會包含該條件塊中提出的問題。

在這種情況下,我們將更改 errorDiv 中的文本 以紅色顯示我們的錯誤:

if (incorrectInput !== "") {
    // Change the error div tag to display the error message(s)
    errorDiv.innerText = incorrectInput; 
    // Change the color of the text to red
    errorDiv.style.color = 'red'; 
    // Prevent the form button from submitting again, before fixing the issues
    error.preventDefault(); 
}

測試代碼

現在,讓我們使用以下輸入來測試我們的新表單:

  • 用戶名:johndoe
  • 密碼:42
  • 確認密碼:421

這應該會產生以下結果:

結論

在本文中,我們使用 vanilla JavaScript 來驗證一個簡單的 HTML 表單。

JavaScript 使我們能夠定義適合我們用例的自定義驗證檢查。例如,您可以添加密碼必須滿足的自定義模式,用戶才能在您的網站上註冊。


Tutorial JavaScript 教程
  1. JavaScript 數組 .reduce 與 async/await

  2. 抽像簡單:可拋出

  3. Vue 路由器:路由解析器

  4. 提交新交易時,moment.js 中的日期不會更改,仍然保存上次日期,直到刷新服務器

  5. 使用 Telegram Bot 與您的 Javascript 應用程序保持聯繫

  6. 狀態機出現:使用操作更新 XState 上下文 (13/24)

  7. 如何將指令從 main.js 移動到外部文件 Vue 3

  1. 使用 Javascript 檢查數組中是否存在值。

  2. Highcharts:無法讀取未定義的屬性“parts/Globals.js”

  3. 為 Nasas Astronomy API 製作更漂亮的網頁

  4. Javascript:this 關鍵字 [上下文] 備忘單

  5. 為什麼我要建立一個數字政府

  6. 使用 MongoDB Realm 實現無服務器 - React.js 版本

  7. React 開發人員的反應式編程第 2 部分 - 與 React 集成

  1. 構建矩陣——來自建築師的筆記

  2. 在 JavaScript 中設計 API 方法

  3. 如何使用 HTML、CSS 和 Vanilla JavaScript 構建天氣轉換器(第 3 部分 - 添加 CSS)

  4. 從顏色中查找最接近的 RGB 分量