溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

jQuery如何實(shí)現(xiàn)高度靈活的表單驗(yàn)證功能

發(fā)布時(shí)間:2020-07-29 12:44:08 來(lái)源:億速云 閱讀:158 作者:小豬 欄目:web開(kāi)發(fā)

這篇文章主要講解了jQuery如何實(shí)現(xiàn)高度靈活的表單驗(yàn)證功能,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

表單驗(yàn)證是前端開(kāi)發(fā)過(guò)程中常見(jiàn)的一個(gè)需求,產(chǎn)品需求、業(yè)務(wù)邏輯的不同,表單驗(yàn)證的方式方法也有所區(qū)別。而最重要的是我們要清楚,表單驗(yàn)證的核心原則是——錯(cuò)誤信息提示準(zhǔn)確,并且盡可能少的打擾/干擾用戶的輸入和體驗(yàn)。

基于以上原則,個(gè)人總結(jié)出表單驗(yàn)證的通用方法論:

為了使開(kāi)發(fā)思路更加清晰,我將表單驗(yàn)證的過(guò)程分為兩步:第一步,用戶輸入完驗(yàn)證當(dāng)前輸入的有效性;第二步,表單提交時(shí)驗(yàn)證整個(gè)表單。考慮如下布局:

<form action="">
  <ul>
    <li><label for="username">用戶名</label>
      <input type="text" name="username" id="username" placeholder="用戶名"/></li>
    <li>
      <label for="password">密碼</label>
      <input type="text" name="password" id="password" placeholder="密碼"/>
    </li>
    <li>
      <label for="password">確認(rèn)密碼</label>
      <input type="text" name="password2" id="password-confirm" placeholder="確認(rèn)密碼"/>
    </li>
    <li>
      <label for="phone">手機(jī)</label>
      <input type="text" name="mobile" id="phone"/>
    </li>
    <li>
      <label for="email">郵箱</label>
      <input type="text" name="email" id="email"/>
    </li>
  </ul>

  <button type="submit" id="submit-btn">提交</button>

</form>

一個(gè)較為通用的JS驗(yàn)證版本如下:

(function (window, $, undefined) {
  /**
   * @param {String}    $el       表單元素
   * @param {[Array]}    rules      自定義驗(yàn)證規(guī)則
   * @param {[Boolean]}   isCheckAll   表單提交前全文驗(yàn)證
   * @param {[Function]}  callback    全部驗(yàn)證成功后的回調(diào)
   * rules 支持四個(gè)字段:name, rule, message, equalTo
   */
  function Validator($el, rules, isCheckAll, callback) {
    var required = 'required';
    var params = Array.prototype.slice.call(arguments);
    this.$el = $el;
    this._rules = [
      {// 用戶名
        username: required,
        rule: /^[\u4e00-\u9fa5\w]{6,12}$/,
        message: '不能包含敏感字符'
      }, {// 密碼
        password: required,
        rule: /^(&#63;![0-9]+$)(&#63;![a-zA-Z]+$)[0-9A-Za-z_@]{6,20}$/,
        message: '只支持?jǐn)?shù)字字母下劃線,且不為純數(shù)字或字母'
      }, {// 重復(fù)密碼
        password2: required,
        rule: /^(&#63;![0-9]+$)(&#63;![a-zA-Z]+$)[0-9A-Za-z_@]{6,20}$/,
        message: '只支持?jǐn)?shù)字字母下劃線,且不為純數(shù)字或字母',
        equalTo: 'password'
      }, {// 手機(jī)
        mobile: required,
        rule: /^1[34578]\d{9}$/,
        message: '請(qǐng)輸入有效的手機(jī)號(hào)碼'
      }, {// 驗(yàn)證碼
        code : required,
        rule: /^\d{6}$/,
        message: '請(qǐng)輸入6位數(shù)字驗(yàn)證碼'
      }, {// 郵箱
        email : required,
        rule: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
        message: '請(qǐng)輸入正確的郵箱'
      }
    ];
    this.isCheckAll = false;
    this.callback = callback;
    // 合并參數(shù)
    this._rules = this._rules.concat(params[1]);
    if(params[2]) {
      if(typeof params[2] == 'function') {
        this.callback = params[2];
      }else {// 提交表單時(shí)是否開(kāi)啟全部驗(yàn)證
        this.isCheckAll = params[2];
      }
    }
    // 用于存儲(chǔ)合去重后的參數(shù)
    this.rules = [];
  }

  Validator.prototype._getKey = function (obj) {
    var k = '';
    for(var key in obj) {
      if(obj.hasOwnProperty(key)) {
        if( key !== 'rule' && key !== 'message' && key !== 'equalTo') {
          k = key;
        }
      }
    }
    return k;
  };
  /**
   * 數(shù)組對(duì)象重復(fù)數(shù)據(jù)進(jìn)行合并,后面的覆蓋前面的
   */
  Validator.prototype.filterRules = function (arrObj) {
    var _this = this,
      h = {},
      res = [],
      arrObject = this._rules;
    $.each(arrObject, function (i, item) {
      var k = _this._getKey(item);
      try {
        if(!h[k] && h[k] !== 0) {
          h[k] = i;
          res.push(item);
        }else {
          res[h[k]] = $.extend(res[h[k]], item);
        }
      }catch(e) {
        throw new Error('不是必填')
      }
    });
    this.rules = res;
  };

  Validator.prototype.check = function () {
    var _this = this;
    $.each(_this.rules, function (i, item) {
      var key = _this._getKey(item),
        reg = item.rule,
        equalTo = item.equalTo,
        errMsg = item.message;

      _this.$el.find('[name='+key+']')
        .on('blur', function () {
          var $this = $(this),
            errorMsg = '',
            val = $this.val(),
            ranges = reg.toString().match(/(\d*,\d*)/),
            range = '',
            min = 0,
            max = 0,
            placeholderTxt = $(this).attr("placeholder") &#63; $(this).attr("placeholder") : '信息';

          // 定義錯(cuò)誤提示信息
          if(val && val != 'undefined') { // 值不為空

            if(ranges) { // 邊界限定
              range = ranges[0];
              min = range.split(',')[0] &#63; range.split(',')[0].trim() : 0;
              max = range.split(',')[1] &#63; range.split(',')[1].trim() : 0;
              if(val.length < min || val.length > max) { // 處理邊界限定的情況
                if(min && max) {
                  errorMsg = '<span class="error-msg">請(qǐng)輸入'+min+'-'+max+'位'+placeholderTxt+'</span>';
                }else if(min) {
                  errorMsg = '<span class="error-msg">最少輸入'+min+'位'+placeholderTxt+'</span>';
                }else if(max) {
                  errorMsg = '<span class="error-msg">最多輸入'+max+'位'+placeholderTxt+'</span>';
                }
              }else { // 邊界正確但匹配錯(cuò)誤
                errorMsg = '<span class="error-msg">'+errMsg+'</span>';

              }
            }else { // 沒(méi)有邊界限定
              errorMsg = '<span class="error-msg">'+errMsg+'</span>';
            }

            if(equalTo) {
              var equalToVal = _this.$el.find('[name='+equalTo+']').val();
              if(val !== equalToVal) {
                errorMsg = '<span class="error-msg">兩次輸入不一致,請(qǐng)重新輸入</span>';
              }
            }

          } else { // 值為空
            errorMsg = '<span class="error-msg">請(qǐng)輸入'+placeholderTxt+'</span>'
          }
          if($('.error-msg').length > 0) return;

          // 驗(yàn)證輸入,顯示提示信息
          if(!reg.test(val) || (equalTo && val !== equalToVal)) {
            if($this.siblings('.error-msg').length == 0) {
              $this.after(errorMsg)
                .siblings('.error-msg')
                .hide()
                .fadeIn();
            }
          }else {
            $this.siblings('.error-msg').remove();
          }
        })
        .on('focus', function () {
          $(this).siblings('.error-msg').remove();
        })
    });

  };
  Validator.prototype.checkAll = function () {
    var _this = this;
    if(_this.isCheckAll) {
      _this.$el.find('[type=submit]')
        .click(function () {
          _this.$el.find('[name]').trigger('blur');
          if($('.error-msg').length > 0) {
            console.log('有錯(cuò)誤信息');
            return false;
          }else {
            console.log('提交成功');
            _this.callback();
          }
        });
      return false;
    }
  };
  Validator.prototype.init = function () {
    this.filterRules();
    this.check();
    this.checkAll();
  };
  $.fn.validator = function (rules, isCheckAll, callback) {
    var validate = new Validator(this, rules, isCheckAll, callback);
    return validate.init();
  };
})(window, jQuery, undefined);

你可以這樣使用:

  var rules = [
    {// 用戶名
      username: 'required',
      rule: /^[\u4e00-\u9fa5\d]{6,12}$/,
      message: '只支持?jǐn)?shù)字loo2222'
    },
    {// 密碼
      password: 'required',
      rule: /^(&#63;![0-9]+$)(&#63;![a-zA-Z]+$)[0-9A-Za-z_@]{6,20}$/,
      message: 'mimmimmia'
    },
    {// 重復(fù)密碼
      password2: 'required',
      rule: /^(&#63;![0-9]+$)(&#63;![a-zA-Z]+$)[0-9A-Za-z_@]{6,20}$/,
      message: '只支持?jǐn)?shù)字字母下劃線,不能為純數(shù)字或字母2222',
      equalTo: 'password'
    },
    {// 座機(jī)
      telephone : 'required',
      rule: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      message: '請(qǐng)輸入正確的座機(jī)'
    }
  ];
  $('form').validator(rules, true)

看完上述內(nèi)容,是不是對(duì)jQuery如何實(shí)現(xiàn)高度靈活的表單驗(yàn)證功能有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI