jQuery實(shí)現(xiàn)高度靈活的表單驗(yàn)證功能示例【無(wú)UI】
本文實(shí)例講述了jQuery實(shí)現(xiàn)高度靈活的表單驗(yàn)證功能。分享給大家供大家參考,具體如下:
表單驗(yàn)證是前端開(kāi)發(fā)過(guò)程中常見(jiàn)的一個(gè)需求,產(chǎn)品需求、業(yè)務(wù)邏輯的不同,表單驗(yàn)證的方式方法也有所區(qū)別。而最重要的是我們要清楚,表單驗(yàn)證的核心原則是——錯(cuò)誤信息提示準(zhǔn)確,并且盡可能少的打擾/干擾用戶的輸入和體驗(yàn)。
該插件依賴于jQuery,demo地址:https://github.com/CaptainLiao/zujian/tree/master/validator
基于以上原則,個(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: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_@]{6,20}$/, message: '只支持?jǐn)?shù)字字母下劃線,且不為純數(shù)字或字母' }, {// 重復(fù)密碼 password2: required, rule: /^(?![0-9]+$)(?![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") ? $(this).attr("placeholder") : '信息'; // 定義錯(cuò)誤提示信息 if(val && val != 'undefined') { // 值不為空 if(ranges) { // 邊界限定 range = ranges[0]; min = range.split(',')[0] ? range.split(',')[0].trim() : 0; max = range.split(',')[1] ? 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: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_@]{6,20}$/, message: 'mimmimmia' }, {// 重復(fù)密碼 password2: 'required', rule: /^(?![0-9]+$)(?![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)
PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測(cè)試工具:
http://tools.jb51.net/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于jQuery相關(guān)內(nèi)容可查看本站專(zhuān)題:《jQuery正則表達(dá)式用法總結(jié)》、《jQuery字符串操作技巧總結(jié)》、《jQuery操作xml技巧總結(jié)》、《jQuery擴(kuò)展技巧總結(jié)》、《jquery選擇器用法總結(jié)》及《jQuery常用插件及用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。
- jquery validate.js表單驗(yàn)證的基本用法入門(mén)
- jquery表單驗(yàn)證使用插件formValidator
- 使用 jQuery 實(shí)現(xiàn)表單驗(yàn)證功能
- 基于Jquery實(shí)現(xiàn)表單驗(yàn)證
- jQuery 表單驗(yàn)證插件formValidation實(shí)現(xiàn)個(gè)性化錯(cuò)誤提示
- jQuery實(shí)現(xiàn)用戶注冊(cè)的表單驗(yàn)證示例
- jquery實(shí)現(xiàn)表單驗(yàn)證并阻止非法提交
- jquery 實(shí)現(xiàn)表單驗(yàn)證功能代碼(簡(jiǎn)潔)
- jquery實(shí)現(xiàn)表單驗(yàn)證簡(jiǎn)單實(shí)例演示
- jquery表單驗(yàn)證插件(jquery.validate.js)的3種使用方式
- jQuery插件Validate實(shí)現(xiàn)自定義表單驗(yàn)證
相關(guān)文章
jQuery-App輸入框?qū)崿F(xiàn)實(shí)時(shí)搜索
這篇文章主要為大家詳細(xì)介紹了jQuery-App輸入框?qū)崿F(xiàn)實(shí)時(shí)搜索,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11Tinymce+jQuery.Validation使用產(chǎn)生的BUG
在IE6下,當(dāng)頁(yè)面有advanced模式的Tinymce編輯器,并且,并且jquery.validation使用了jquery.metadata時(shí)會(huì)出現(xiàn)以下問(wèn)題2010-03-03jQuery實(shí)現(xiàn)對(duì)無(wú)序列表的排序功能(附demo源碼下載)
這篇文章主要介紹了jQuery實(shí)現(xiàn)對(duì)無(wú)序列表的排序功能,涉及jQuery與javascript常見(jiàn)的文本操作函數(shù)與sort排序函數(shù)的相關(guān)使用方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06HTML5使用DeviceOrientation實(shí)現(xiàn)搖一搖功能
這篇文章主要介紹了HTML5使用DeviceOrientation實(shí)現(xiàn)搖一搖功能的相關(guān)資料,需要的朋友可以參考下2015-06-06jquery瀏覽器滾動(dòng)加載技術(shù)實(shí)現(xiàn)方案
Google閱讀器上有一個(gè)AJAX效果很不錯(cuò),就是閱讀項(xiàng)目時(shí)不需要翻頁(yè),瀏覽器滾動(dòng)條往下拉到一定位置時(shí)自動(dòng)加載新的一批項(xiàng)目進(jìn)來(lái),一直到所有項(xiàng)目加載完為止。對(duì)于我來(lái)說(shuō)再好不過(guò)了,因?yàn)槲液懿幌矚g翻頁(yè),尤其是輸入頁(yè)碼再定位到頁(yè)。2014-06-06jquery實(shí)現(xiàn)進(jìn)度條狀態(tài)展示
這篇文章主要為大家詳細(xì)介紹了jquery實(shí)現(xiàn)進(jìn)度條狀態(tài)展示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03Query常用DIV操作獲取和設(shè)置長(zhǎng)度寬度的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇Query常用DIV操作獲取和設(shè)置長(zhǎng)度寬度的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09jQuery模擬爆炸倒計(jì)時(shí)功能實(shí)例代碼
本文通過(guò)代碼給大家介紹了jQuery模擬爆炸倒計(jì)時(shí)功能實(shí)例代碼,非常不錯(cuò),代碼簡(jiǎn)單易懂,需要的朋友參考下吧2017-08-08