DIV CSS 佈局教程網

jQuery 自定義數據驗證插件(簡單練手)實例代碼
編輯:JQuery特效代碼     

為了加深對 jQuery 插件開發的理解,本文動手寫一個簡單的數據驗證插件。它支持多種常見格式的校驗,並能在驗證失敗時以彈窗或頁面提示的方式給出反饋。

插件實現

(function($) {
  var defaults = {
    bugColor: '#FFCCCC', //數據有誤的時候文本框顏色
    color: 'white', //數據正確時候文本框顏色
    type: "alert", //數據錯誤時候提示方式 alert 彈出框方式 text 賦值 span html
    msg: "Msg", //數據有誤的時候提示內容
    ResOjId: 'no' //當 type 為 text 時被賦值的標簽 #id
  };
  function UiProcess(options, rexString, object) {
    var options = $.extend(defaults, options);
    var values = object.val();
    if (rexString.test(values)) {
      object.css("backgroundColor", options.color);
      return true;
    } else {
      object.css("backgroundColor", options.bugColor);
      if (options.type == "alert") { alert(options.msg); }
      if (options.type == "text") { $(options.ResOjId).html(options.msg); }
      return false;
    }
  }
  //驗證 ip 是否符合格式
  $.fn.RegIp = function(options) {
    var rexString = /^\d{1,3}\.{1}\d{1,3}\.{1}\d{1,3}/;
    return UiProcess(options, rexString, this)
  }
  //驗證座機是否符合格式
  $.fn.RegTelPhone = function(options) {
    var rexString = /^[0-9]+[-]?[0-9]+[-]?[0-9]$/;
    return UiProcess(options, rexString, this)
  }
  //驗證手機是否符合格式
  $.fn.RegMombilePhone = function(options) {
    var rexString = /(^189\d{8}$)|(^13\d{9}$)|(^15\d{9}$)/;
    return UiProcess(options, rexString, this)
  }
  //驗證中文是否符合格式
  $.fn.RegCHZN = function(options) {
    var rexString = /[\u4e00-\u9fa5]/;
    return UiProcess(options, rexString, this)
  }
  //驗證 decimal 是否符合格式
  $.fn.RegDecimal = function(options) {
    var rexString = /^[0-9]+[.]?[0-9]+$/;
    return UiProcess(options, rexString, this)
  }
  //驗證整數是否符合格式
  $.fn.RegNumber = function(options) {
    var rexString = /^[0-9]+$/;
    return UiProcess(options, rexString, this)
  }
  //驗證非空字符
  $.fn.IsEmpty = function(options) {
    var rexString = /(^.+$)|([\u4e00-\u9fa5])/;
    return UiProcess(options, rexString, this)
  }
})(jQuery);

調用方式

<script type="text/javascript">
  function submitOk() {
    var interfaceNameInput = $("#<%=interfaceName.ClientID %>");
    var userNameInput = $("#<%=userName.ClientID %>");
    if (!interfaceNameInput.IsEmpty({ "msg": "接口名稱格式不正確!" })) { return false }
    if (!userNameInput.IsEmpty({ "msg": "格式不正確!" })) { return false }
  }
</script>

這個插件把公共的驗證邏輯抽取到 UiProcess 函數中,各個驗證方法只需提供對應的正則表達式即可,結構清晰、易於擴展。驗證通過時輸入框變為正常顏色並返回 true,失敗時變為警示顏色、給出提示並返回 false。

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