DIV CSS 佈局教程網

用 jQuery + 正則表達式做一次統一的表單驗證
編輯:關於JavaScript     

表單驗證一向瑣碎,欄位一多更是惡夢——每個 input 都單獨寫一段判斷,程式碼膨脹得不成樣子。後來寫了一小段 JS,把驗證規則集中管理,從此不必再為每個欄位量身打造。

用法:把正則寫進自訂屬性

<input type="text" dataType="正則表達式" />

規則直接寫在標籤上,提交按鈕只要綁一個 checkForm 函式,就具備整表驗證能力。

核心程式

// 表單驗證(例如「下一步」按鈕的事件)
function checkForm(form) {
  var success = true;
  $("." + form + " input").each(function () {
    var $that = $(this);
    var dataType = eval($that.attr("dataType"));
    if (dataType != undefined) {
      if ($that.val().match(dataType)) {
        $that.removeClass("borderRed");
      } else {
        $that.focus();
        $that.addClass("borderRed");
        success = false;
        return false; // 中斷 each
      }
    }
  });
  return success;
}

// 為所有帶 dataType 的標籤即時回饋
$(document).on("blur", "input", function () {
  var $that = $(this);
  var dataType = eval($that.attr("dataType"));
  if (dataType != undefined) {
    if ($that.val().match(dataType)) {
      $that.removeClass("borderRed");
    } else {
      $that.addClass("borderRed");
    }
  }
});

// 聚焦時先移除錯誤樣式,給使用者重新開始的機會
$(document).on("focus", "input", function () {
  $(this).removeClass("borderRed");
});

實際 markup 範例

<input type="text" dataType="/^1[3-9]\d{9}$/" />   <!-- 手機號碼 -->
<input type="text" dataType="/^\w+@\w+\.\w+$/" /> <!-- 電子郵件 -->

兩個設計值得留意:一是用事件委派 $(document).on() 綁定,動態插入的欄位也自動生效;二是 blur 時就給回饋、focus 時清掉紅框,比只在按下送出才一次爆錯友善得多。想再往前一步,可以把提示文字也做成 data 屬性一併帶出。

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