DIV CSS 佈局教程網

不靠插件:用原生 jQuery 手寫一個表單驗證
編輯:JQuery入門技巧     

jquery.validate 很好用,但有時候需求很簡單,或者不想多載一個檔案。這種時候自己寫反而更輕。以下示範用 jQuery 做一個具備「必填標記 + 失焦提示 + 提交攔截」的表單驗證。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>jQuery 表單驗證</title>
<script src="js/jquery-1.3.1.js"></script>
<style>
body { font: 12px/19px Arial, Helvetica, sans-serif; color: #666; }
form div { margin: 5px 0; }
.int label { float: left; width: 100px; text-align: right; }
.int input { padding: 1px; border: 1px solid #ccc; height: 16px; }
.sub { padding-left: 100px; }
.sub input { margin-right: 10px; }
.formtips { width: 200px; margin: 2px; padding: 2px; }
.onError   { background: #FFE0E9 url(images/reg3.gif) no-repeat 0 center; padding-left: 25px; }
.onSuccess { background: #E9FBEB url(images/reg4.gif) no-repeat 0 center; padding-left: 25px; }
.high { color: red; }
</style>
<script>
$(function () {
  // 一、為 class 含 required 的欄位自動補上紅色星號
  $("form :input.required").each(function () {
    var $required = $("<strong class='high'>*</strong>");
    $(this).parent().append($required);
  });

  // 二、欄位失去焦點時即時驗證
  $("form :input").blur(function () {
    var $parent = $(this).parent();
    // 先清掉舊提示,避免訊息越堆越多
    $(".formtips").remove();

    if ($(this).is("#username")) {
      if (this.value == '' || this.value.length < 6) {
        $parent.append('<span class="formtips onError">請輸入正確的格式.</span>');
      } else {
        $parent.append('<span class="formtips onSuccess">格式輸入正確</span>');
      }
    }

    if ($(this).is("#email")) {
      // 郵箱格式:以正則表達式檢查
      if (this.value == '' || (this.value != "" && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value))) {
        $parent.append('<span class="formtips onError">請輸入正確的格式.</span>');
      } else {
        $parent.append('<span class="formtips onSuccess">格式輸入正確</span>');
      }
    }
  });

  // 三、按下提交時,若仍有錯誤就攔住
  $("#send").click(function () {
    // 只要畫面上存在 .onError 元素,代表還有未通過的欄位
    var onerr = $(this).parent().siblings().children().hasClass("onError");
    if (onerr) {
      return false;
    } else {
      alert("你已經注冊成功了");
    }
  });

  // 四、重設時清掉提示
  $("#reset").click(function () {
    $(".formtips").remove();
  });
});
</script>
</head>
<body>
<form method="post" action="">
  <div class="int">
    <label for="username">用戶名:</label>
    <input type="text" id="username" class="required"/>
  </div>
  <div class="int">
    <label for="email">郵箱:</label>
    <input type="text" id="email" class="required"/>
  </div>
  <div class="int">
    <label for="personinfo">個人資料:</label>
    <input type="text" id="personinfo"/>
  </div>
  <div class="sub">
    <input type="submit" value="提交" id="send"/>
    <input type="reset" value="重設" id="reset"/>
  </div>
</form>
</body>
</html>

這個版本可以更好的地方

1. 用 change 取代部分 blur。blur 只有離開欄位才觸發,對下拉選單或 checkbox 用 change 更合適。

2. 提示訊息要具體。「請輸入正確的格式」對使用者幫助有限,寫成「用戶名至少 6 個字元」或「請輸入有效的 Email 位址」體驗更好。

3. 別用 .remove() 全域清除提示。範例中 $(".formtips").remove() 會把其他欄位的提示一起清掉。改成 $(this).parent().find('.formtips').remove() 只影響當前欄位。

4. 校驗邏輯抽成函式。把每個欄位的規則寫成獨立 function,提交時逐一呼叫並回傳 false,可讀性與可維護性都會提升。

5. 提交按鈕的判斷依賴 DOM 狀態。用「畫面上有沒有 .onError」來決定能否提交,比重新跑一次驗證可靠,建議提交時直接觸發所有欄位的 blur 再判斷。

以上就是純手寫的 jQuery 表單驗證範例,適合需求簡單、不想引入額外套件的場景;若欄位多、規則複雜,還是 recommend 用成熟的驗證庫。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved