How to use validMethods method in wpt

Best JavaScript code snippet using wpt

jquery.validator.js

Source:jquery.validator.js Github

copy

Full Screen

1/**2 * @file 基于 jQuery 的 validator 插件3 * @author ZwB4 * @version 1.05 * @module validator6 * @require jquery7 * @method $.validator8 * @desc9 * <pre>10 * validType 验证类型 对象集合 每一个属性都是一种验证类别 每一个属性对应一个对象11 该对象中的属性名 对应着执行验证的方法 值为提示信息12 * validMethods 验证方法 对象集合 每一个方法都是使用 apply 方式被调用,方法中的 this 是进行验证的 jQuery 对象13 * </pre>14 * @param {object} options15 * @param {(string|object)} options.selector 需要验证的表单对象16 * @param {function(string)} options.normal 重置表单时的操作17 * @param {function(string)} options.focus 表单项获得焦点时的操作18 * @param {function(string)} options.wrong 表单项未通过验证时的操作19 * @param {function(string)} options.right 表单项通过验证时的操作20 * @return {object} 参数 selector 所对应的 jQuery 对象21 * @example22 * JavaScript 代码:23 $(function(){24 $.validator.validType.username = {// 用户名 验证配置25 type: ['required', '请填写用户名'],26 trim: true, // 验证时对值进行 trim27 focus: '请输入6~12位数字、字母、下划线组合,并以字母开头', // 获得焦点时的操作28 valid:[29 ['regexp', /^[a-z]/i],30 ['regexp', /^[a-z0-9_]$/i],31 ['length', 6, 20],32 ['ajax', 'url', '']33 ],34 text:['只能字母开头', '只能输入数字、字母、下划线组合', '只能输入6~12位字符', '该用户名已被注册,请尝试其他用户名'],35 right:'',36 callback:function(rs){alert(rs?'通过验证':'未通过验证')} // 验证后的回调函数37 };38 var $userNameForm = $.validator({39 selector: '#userNameForm',40 normal:function(txt){41 this.next().empty();42 },43 focus:function(txt){44 this.next().html( txt );45 },46 wrong:function(txt){47 alert(txt);48 },49 right:function(txt){50 alert('通过验证');51 }52 });53 })54 * HTML 代码:55 <form id="userNameForm" action="">56 <input type="text" name="username" id="username" data-validator="username" /><span></span>57 </form>58 * @todo 重构59 * @todo submit 事件可以不触发60 * */61;(function(factory, jqPath){62 if( typeof exports === 'object' && typeof module === 'object' ){63 factory( require(jqPath || 'jquery') );64 }65 else if( typeof define === 'function' && define.amd ){66 define([jqPath || 'jquery'], factory);67 }68 else{69 factory(jQuery);70 }71})(function($){72 'use strict';73 var methods = {74 valid: function(){75 var $items = this.find('[data-validator]')76 , i = $items.length77 , validType = $.validator.validType78 , $item79 , type80 , result = true81 ;82 while( i-- ){83 $item = $items.eq(i);84 type = $item.data('validator');85 if( typeof type === 'string' ){86 type = validType[type] || {};87 $item.data('validator', type);88 }89 result = this.triggerHandler('valid', [$item, type]) && result;90 }91 return result;92 }93 , reset: function(deep){ // 重置表单94 var $items = this.find('[data-validator]')95 , i = $items.length96 , normal = this.validOpts.normal97 ;98 deep && this.get(0).reset(); // 重置表单项的值99 while( i-- ){100 normal.apply( $items.eq(i) );101 }102 }103 , result: function(){ // 返回表单数据104 var array = this.serializeArray()105 , data = {}106 , temp107 , i = array.length108 ;109 while( i-- ){110 temp = array[i];111 if( temp.name in data ){112 data[temp.name] += ','+ temp.value;113 }114 else{115 data[temp.name] = temp.value;116 }117 }118 return data;119 }120 }121 , log = function( msg ){122 console && console.log && console.log( msg );123 }124 ;125 /**126 * @namespace Validator127 * */128 var Validator = function( options ){129 var opts = $.extend({}, Validator.defaults, options)130 , $form = opts.selector131 , validType = Validator.validType132 , validMethods = Validator.validMethods133 , validEvent = Validator.validEvent134 , validTrigger = function(){135 var $self = $(this)136 , type = $self.data('validator')137 ;138 if( typeof type === 'string' ){139 type = validType[type] || {};140 $self.data('validator', type);141 }142 $form.triggerHandler('valid', [$self, type]);143 }144 , k145 ;146 $form = (typeof $form === 'object' && $form.jQuery) ? $form : $($form);147 $form.on({148 'submit.validator': function(e){149 var rs = $form.valid();150 if( !rs ){151 e.stopImmediatePropagation();152 }153 return rs;154 }155 , 'reset.validator': function(e){156 $form.reset();157 }158 , valid: function(e, $item, type){159 var methods = type.valid || []160 , i = 0161 , j = methods.length162 , validTemp163 , validName164 , validText165 , result = true166 , isValid = true167 , isRequired = false168 , required = validMethods.required169 , wrong = opts.wrong170 ;171 if( 'trim' in type ){172 $item.val(function(){173 return $.trim( this.value );174 });175 }176 if( 'type' in type ){ // 验证类型177 isRequired = true;178 validTemp = type.type.slice(0);179 validName = validTemp.shift();180 validText = validTemp.pop();181 // 判断当前值是否为空182 isValid = required.call($item);183 if( validName === 'required' ){ // 必填验证 已经验证184 }185 else if( validName === 'or' ){ // 多选一验证186 if( !isValid ){187 isValid = false;188 isRequired = !validMethods.or.apply($item, validTemp);189 }190 }191 else if( validName === 'and' ){ // 多项同时填写192 isValid = isValid && validMethods.and.apply($item, validTemp);193 isRequired = false;194 }195 else{ // 自定义,视为选填项,根据返回结果是否继续验证196 isValid = validMethods[validName].apply($item);197 isRequired = false;198 }199 result = isValid;200 }201 else{ // 未设置 为选填202 isValid = required.call($item);203 }204 if( isValid ){ // 继续验证205 for(; i < j; i++){206 validTemp = methods[i].slice();207 validName = validTemp.shift();208 result = validMethods[validName].apply($item, validTemp) && result;209 if( !result ){210 wrong.call($item, type.text[i] || type.text[0]);211 break;212 }213 }214 }215 else{216 if( isRequired ){217 wrong.call($item, validText);218 result = false;219 }220 else{221 opts.normal.call($item);222 result = true;223 }224 }225 if( result ){ // 通过验证226 if( 'right' in type && isValid ){227 opts.right.call($item, type.right);228 }229 else{230 opts.normal.call($item);231 }232 }233 if( 'callback' in type ){234 type.callback.call($item, result);235 }236 return result;237 }238 }).on('focus.validator', '[data-validator]', function(){239 var $self = $(this)240 , type = $self.data('validator')241 ;242 if( typeof type === 'string' ){243 type = validType[type] || {};244 $self.data('validator', type);245 }246 if( ('focus' in type) && ('focus' in opts) ){247 opts.focus.call($self, type.focus);248 }249 });250 for( k in validEvent ) if( validEvent.hasOwnProperty(k) ){251 $form.on(validEvent[k] +'.validator', k +'[data-validator]', validTrigger);252 }253 $form.validOpts = opts;254 $.extend($form, methods);255 return $form;256 };257 Validator.defaults = {258 selector:''259 , focus:null260 , wrong:null261 , right:null262 , normal:null263 };264 /**265 * @memberof Validator266 * @namespace validType267 * @desc 验证类型集合268 * @example269 $.validator.validType.username = {// 用户名 验证配置270 type: ['required', '请填写用户名'],271 trim: true, // 验证时对值进行 trim272 focus: '请输入6~12位数字、字母、下划线组合,并以字母开头', // 获得焦点时的操作273 valid:[274 ['regexp', /^[a-z]/i],275 ['regexp', /^[a-z0-9_]$/i],276 ['length', 6, 20],277 ['ajax', 'url', '']278 ],279 text:['只能字母开头', '只能输入数字、字母、下划线组合', '只能输入6~12位字符', '该用户名已被注册,请尝试其他用户名'],280 right:'',281 callback:function(rs){alert(rs?'通过验证':'未通过验证')} // 验证后的回调函数282 };283 * */284 Validator.validType = {};285 /**286 * @memberof Validator287 * @namespace validEvent288 * @desc 验证事件类型289 * 默认事件类型:290 * <pre>291 selector 事件292 :text blur293 :password blur294 :radio click295 :checkbox click296 select change297 textarea blur298 * </pre>299 * */300 Validator.validEvent = {301 ':text': 'blur'302 , ':password': 'blur'303 , ':radio': 'click'304 , ':checkbox': 'click'305 , 'select': 'change'306 , 'textarea': 'blur'307 };308 /**309 * @memberof Validator310 * @namespace validMethods311 * @desc 验证方法集合312 * */313 Validator.validMethods = {314 /**315 * 必填项验证316 * */317 /**318 * @memberof Validator.validMethods319 * @method required320 * @return {boolean} 验证结果321 * @desc 验证是否为空322 * */323 required: function(){324 var result = false;325 if( this.is(':radio,:checkbox') ){326 result = ( this.parents('form').find('input[name="'+ this.attr('name') +'"][data-validator]:checked').length > 0 );327 }328 else{329 result = !!this.val();330 }331 return result;332 }333 /**334 * @method or335 * @memberof Validator.validMethods336 * @param {string=} selector 参数至少 1 个 为 jquery 选择器337 * @return {boolean} 验证结果338 * @desc 检测当前标签与目标标签至少一个不为空,参数至少 1 个 为 jquery 选择器339 * */340 , or: function(selector){341 var required = Validator.validMethods.required342 , result = required.apply( this )343 , argc = arguments.length344 , i = 0345 ;346 if( argc < 1 ){347 log('参数设置错误');348 result = false;349 }350 else{351 for(; i < argc; i++){352 if( result ) break;353 result = result || required.apply( $(arguments[i]) );354 }355 }356 return result;357 }358 /**359 * @method and360 * @memberof Validator.validMethods361 * @param {string=} selector 参数至少 1 个 为 jquery 选择器362 * @return {boolean} 验证结果363 * @desc 检测当前标签与目标标签同时不为空,参数至少 1 个 为 jquery 选择器364 * */365 , and: function(selector){366 var required = Validator.validMethods.required367 , result = required.apply( this )368 , argc = arguments.length369 , i = 0370 ;371 if( argc < 1 ){372 log('参数设置错误');373 result = false;374 }375 else{376 for(; i < argc; i++){377 if( !result ) break;378 result = result && required.apply( $(arguments[i]) );379 }380 }381 return result;382 }383 /**384 * 特殊标签验证385 * */386 /**387 * @method select388 * @memberof Validator.validMethods389 * @param {number} min 最小选择个数390 * @param {number=} max 最大选择个数(可选)391 * @return {boolean} 验证结果392 * @desc 检测设置了 multiple 属性的 select 标签的可选个数,至少 1 个参数,参数 1 为最小选择个数,参数 2 为最大选择个数(可选),其余参数忽略393 * */394 , select: function(min, max){395 var result = false396 , argc397 , numSelect398 ;399 if( this.is('select') && this.attr('multiple') === 'multiple' ){400 // 是 select 标签并且 select 标签设置了 multiple 属性401 argc = arguments.length;402 numSelect = this.find(':selected').length;403 if( argc === 1 ){404 result = ( numSelect >= min );405 }406 else if( argc > 1 ){407 result = ( numSelect >= min && numSelect <= max );408 }409 else{410 log('参数设置错误');411 }412 }413 else{414 // 不是 select 标签或 select 标签没有 multiple 属性415 log('标签设置错误');416 }417 return result;418 }419 /**420 * @method checkbox421 * @memberof Validator.validMethods422 * @param {number} min 最小选择个数423 * @param {number=} max 最大选择个数(可选)424 * @return {boolean} 验证结果425 * @desc 检测 checkbox 的可选个数,至少 1 个参数,参数 1 为最小选择个数,参数 2 为最大选择个数(可选),其余参数忽略426 * */427 , checkbox: function(min, max){428 var result = false429 , argc430 , numChecked431 ;432 if( !this.is(':checkbox') ){433 log('标签错误');434 }435 else{436 argc = arguments.length;437 numChecked = this.parents('form').find('input[name="'+ this.attr('name') +'"][data-validator]:checkbox:checked').length;438 if( argc === 1 ){439 result = ( numChecked >= min );440 }441 else if( argc > 1 ){442 result = ( numChecked >= min && numChecked <= max );443 }444 else{445 log('参数设置错误');446 }447 }448 return result;449 }450 /**451 * 字符串类型验证452 * */453 /**454 * @method length455 * @memberof Validator.validMethods456 * @param {number} min 最小选择个数457 * @param {number=} max 最大选择个数(可选)458 * @return {boolean} 验证结果459 * @desc 检测字符串长度,至少 1 个参数,参数 1 为最小长度,参数 2 为最大长度(可选),其余参数忽略460 * */461 , length: function(min, max){462 var result = false463 , argc = arguments.length464 , length = this.val().length465 ;466 if( argc === 1 ){467 result = ( length >= min );468 }469 else if( argc > 1 ){470 result = ( length >= min && length <= max );471 }472 else{473 log('未知异常');474 }475 return result;476 }477 /**478 * @method regexp479 * @memberof Validator.validMethods480 * @param {regexp=} regexp481 * @return {boolean} 验证结果482 * @desc 检测是否非法字符,reg 为正则表达式规则 默认值为 /^[a-z0-9_]*$/i483 * */484 , regexp: function( regexp ){485 return (regexp || /^[a-z0-9_]*$/i).test( this.val() );486 }487 /**488 * 比较类型验证489 * */490 /**491 * @method equal492 * @memberof Validator.validMethods493 * @param {*} value 一个固定数据494 * @return {boolean} 验证结果495 * @desc 检测与目标 value 是否相等,参数 value 为一个固定数据496 * */497 , equal: function(value){498 var result = false;499 if( value ){500 result = ( this.val() === value );501 }502 else{503 log('参数设置错误');504 }505 return result;506 }507 /**508 * @method unequal509 * @memberof Validator.validMethods510 * @param {*} value 一个固定数据511 * @return {boolean} 验证结果512 * @desc 检测与目标 value 是否不相等,参数 value 为一个固定数据513 * */514 , unequal: function(value){515 var result = false;516 if( value ){517 result = ( this.val() !== value );518 }519 else{520 log('参数设置错误');521 }522 return result;523 }524 /**525 * @method lt526 * @memberof Validator.validMethods527 * @param {*} value 一个固定数据528 * @param {boolean} equal 是否可以等于 value529 * @return {boolean} 验证结果530 * @desc 检测是否小于目标 value,参数 value 为一个固定数据,equal 是否可以等于 value531 * */532 , lt: function(value, equal){533 var result = false;534 if( value ){535 result = equal ? ( this.val() <= value ) : ( this.val() < value );536 }537 else{538 log('参数设置错误');539 }540 return result;541 }542 /**543 * @method gt544 * @memberof Validator.validMethods545 * @param {*} value 一个固定数据546 * @param {boolean} equal 是否可以等于 value547 * @return {boolean} 验证结果548 * @desc 检测是否大于目标 value,参数 value 为一个固定数据,equal 是否可以等于 value549 * */550 , gt: function(value, equal){551 var result = false;552 if( value ){553 result = equal ? ( this.val() >= value ) : ( this.val() > value );554 }555 else{556 log('参数设置错误');557 }558 return result;559 }560 /**561 * DOM 对象属性值比较类型验证562 * */563 /**564 * @method equalDOMProp565 * @memberof Validator.validMethods566 * @param {string} selector 为 jquery 选择器,若只有一个参数则默认从 val 取值567 * @param {string=} method 为 jquery 方法名(attr,data,html,prop,text,val)568 * @param {string=} name 为属性名569 * @return {boolean} 验证结果570 * @desc 检测与目标 dom 对象的属性值是否相等,至少一个参数,参数 selector 为 jquery 选择器,method 为 jquery 方法名(attr,data,prop,text,html),name 为属性名,若只有一个参数则默认从 val 取值571 * */572 , equalDOMProp: function(selector, method, name){573 var argc = arguments.length574 , result = false575 ;576 if( argc === 1 ){577 result = ( this.val() === $(selector).val() );578 }579 else if( argc > 1 ){580 switch( method ){581 case 'html':582 case 'text':583 case 'val':584 result = ( this.val() === $(selector)[method]() );585 break;586 case 'attr':587 case 'data':588 case 'prop':589 if( name ){590 result = ( this.val() === $(selector)[method]( name ) );591 }592 else{593 log('参数设置错误');594 }595 break;596 default:597 log('参数设置错误');598 break;599 }600 }601 else{602 log('参数设置错误');603 }604 return result;605 }606 /**607 * @method unequalDOMProp608 * @memberof Validator.validMethods609 * @param {string} selector 为 jquery 选择器,若只有一个参数则默认从 val 取值610 * @param {string=} method 为 jquery 方法名(attr,data,html,prop,text,val)611 * @param {string=} name 为属性名612 * @return {boolean} 验证结果613 * @desc 检测与目标 dom 对象的属性值是否不相等,至少一个参数,参数 selector 为 jquery 选择器,method 为 jquery 方法名(attr,data,prop,text,html),name 为属性名,若只有一个参数则默认从 val 取值614 * */615 , unequalDOMProp: function(selector, method, name){616 // 检测与目标 dom 对象的属性值是否不相等,至少一个参数,参数 selector 为 jquery 选择器,method 为 jquery 方法名(attr,data,prop,text,html),name 为属性名,若只有一个参数则默认从 val 取值617 var argc = arguments.length618 , result = false619 ;620 if( argc === 1 ){621 result = ( this.val() !== $(selector).val() );622 }623 else if( argc > 1 ){624 switch( method ){625 case 'html':626 case 'text':627 case 'val':628 result = ( this.val() !== $(selector)[method]() );629 break;630 case 'attr':631 case 'data':632 case 'prop':633 if( name ){634 result = ( this.val() !== $(selector)[method]( name ) );635 }636 else{637 log('参数设置错误');638 }639 break;640 default:641 log('参数设置错误');642 break;643 }644 }645 else{646 log('参数设置错误');647 }648 return result;649 }650 /**651 * @method ltDOMProp652 * @memberof Validator.validMethods653 * @param {string} selector 为 jquery 选择器,若只有一个参数则默认从 val 取值654 * @param {boolean} equal 是否可以与目标值相等655 * @param {string=} method 为 jquery 方法名(attr,data,html,prop,text,val)656 * @param {string=} name 为属性名657 * @return {boolean} 验证结果658 * @desc 检测是否小于等于目标 dom 对象的属性值,至少一个参数,参数 selector 为 jquery 选择器,method 为 jquery 方法名(attr,data,prop,text,html),name 为属性名,若只有一个参数则默认从 val 取值659 * */660 , ltDOMProp: function(selector, equal, method, name){661 var argc = arguments.length662 , result = false663 ;664 if( argc === 1 ){665 result = ( this.val() < $(selector).val() );666 }667 else if( argc > 1 ){668 switch( method ){669 case 'html':670 case 'text':671 case 'val':672 result = ( this.val() < $(selector)[method]() );673 break;674 case 'attr':675 case 'data':676 case 'prop':677 if( name ){678 result = ( this.val() < $(selector)[method]( name ) );679 }680 else{681 log('参数设置错误');682 }683 break;684 default:685 log('参数设置错误');686 break;687 }688 }689 else{690 log('参数设置错误');691 }692 return result;693 }694 /**695 * @method gtDOMProp696 * @memberof Validator.validMethods697 * @param {string} selector 为 jquery 选择器,若只有一个参数则默认从 val 取值698 * @param {boolean} equal 是否可以与目标值相等699 * @param {string=} method 为 jquery 方法名(attr,data,html,prop,text,val)700 * @param {string=} name 为属性名701 * @return {boolean} 验证结果702 * @desc 检测是否大于等于目标 dom 对象的属性值,至少一个参数,参数 selector 为 jquery 选择器,method 为 jquery 方法名(attr,data,prop,text,html),name 为属性名,若只有一个参数则默认从 val 取值703 * */704 , gtDOMProp: function(selector, equal, method, name){705 var argc = arguments.length706 , result = false707 ;708 if( argc === 1 ){709 result = ( this.val() > $(selector).val() );710 }711 else if( argc === 2 ){712 result = ( this.val() >= $(selector).val() );713 }714 else if( argc > 2 ){715 switch( method ){716 case 'html':717 case 'text':718 case 'val':719 result = equal ? ( this.val() >= $(selector)[method]() ) : ( this.val() > $(selector)[method]() );720 break;721 case 'attr':722 case 'data':723 case 'prop':724 if( name ){725 result = equal ? ( this.val() >= $(selector)[method]( name ) ) : ( this.val() > $(selector)[method]( name ) );726 }727 else{728 log('参数设置错误');729 }730 break;731 default:732 log('参数设置错误');733 break;734 }735 }736 else{737 log('参数设置错误');738 }739 return result;740 }741 /**742 * 数字类型验证743 * */744 /**745 * @method isNumber746 * @memberof Validator.validMethods747 * @return {boolean} 检测结果748 * @desc 检测是否为数字 包括负数和小数的情况749 * */750 , isNumber: function(){751 return /^-?\d+\.?\d*$/.test( this.val() );752 }753 /**754 * @method limit755 * @memberof Validator.validMethods756 * @param {number} min 最小值757 * @param {number=} max 最大值(可选)758 * @return {boolean} 验证结果759 * @desc 检测数值大小,至少 1 个参数,参数 1 为最小值,参数 2 为最大值(可选),其余参数忽略760 * */761 , limit: function(min, max){762 var result = false763 , argc = arguments.length764 , value = Number( this.val() )765 ;766 if(argc === 1){767 result = ( value >= min );768 }769 else if(argc > 1){770 result = ( value >= min && value <= max );771 }772 else {773 log('参数设置错误');774 }775 return result;776 }777 /**778 * @method decimal779 * @memberof Validator.validMethods780 * @param {number} digit 小数点右侧的最大位数781 * @param {number=} size 数字的最大位数(可选)782 * @return {boolean} 验证结果783 * @desc 检测浮点型数值,至少 1 个参数,参数 1 为小数点右侧的最大位数,参数 2 为数字的最大位数(可选),其余参数忽略784 * */785 , decimal: function(digit, size){786 var result = false787 , argc = arguments.length788 , regexp789 , temp790 ;791 if( argc === 1 ){792 regexp = new RegExp('^-?\\d+\\.?\\d{0,'+ digit +'}$');793 result = regexp.test( this.val() );794 }795 else if( argc > 1 ){796 temp = size - digit;797 regexp = new RegExp('^-?\\d'+ (temp >= 1 ? '{1'+ (temp === 1 ? '' : ','+ temp) +'}' : '+') +'\\.?\\d{0,'+ digit +'}$');798 result = regexp.test( this.val() );799 }800 else{801 log('参数设置错误');802 }803 return result;804 }805 /**806 * @method exponent807 * @memberof Validator.validMethods808 * @return {boolean} 验证结果809 * @desc 检测指数数值810 * */811 , exponent: function(){812 return /^-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?$/i.test( this.val() );813 }814 /**815 * ajax 验证816 * todo 改成 异步817 * */818 /**819 * @method ajax820 * @memberof Validator.validMethods821 * @param {string} url 服务器链接路径822 * @param {*} expected 对服务器返回结果的期望值823 * @param {string} type 发送 ajax 的类型824 * @param {string|object} param 发送 ajax 时附带的额外参数825 * @return {boolean} 验证结果826 * @desc ajax 将值发送到服务器端进行验证,方法为同步827 * @todo 改成异步828 * @todo 可执行 jsonp829 * */830 , ajax: function(url, expected, type, param){831 var self = this832 , value = self.val()833 , name = self.attr('name')834 ;835 if( param ){836 if( typeof param === 'string' ){837 param += '&' + name + '=' + value;838 }839 else if( typeof param === 'object' ){840 param[name] = value;841 }842 }843 else{844 param = name + '=' + value;845 }846 return expected === $.ajax({847 url: url848 , type: (type ? type : 'GET')849 , data: param850 , async: false851 }).responseText;852 }853 /**854 * 特殊验证类型855 * */856 /**857 * @method url858 * @memberof Validator.validMethods859 * @param {regexp=} regexp 自定义验证正则表达式860 * @return {boolean} 验证结果861 * @desc 检验是否为合法 url,可以自定义验证正则表达式862 * */863 , url: function( regexp ){864 return (regexp || /^(?:http(?:s?):\/\/)?[a-z0-9\u4E00-\u9FA5\-_\.]*[a-z0-9\-_\u4E00-\u9FA5]+(?::(\d+))?\.[a-z0-9\u4E00-\u9FA5]+[0-9a-z\$\-\._'\(\)\/!\?#&\+=%\u4E00-\u9FA5]*/i).test( this.val() );865 }866 /**867 * @method email868 * @memberof Validator.validMethods869 * @param {regexp=} regexp 自定义验证正则表达式870 * @return {boolean} 验证结果871 * @desc 检验是否为合法邮箱,可以自定义验证正则表达式872 * */873 , email: function( regexp ){874 return (regexp || /^(?:[a-z0-9_\-\.'])+@(?:[a-z0-9_\-\.])+\.(?:[a-z]{2,6})$/i).test( this.val() );875 }876 /**877 * @return {boolean} 验证结果878 * @desc 检测是否为中文,正则表达式为 /^[\u4E00-\u9FA5]*$/879 * */880 , isChinese: function(){881 return /^[\u4E00-\u9FA5]*$/.test( this.val() );882 }883 /**884 * @method idNumber885 * @memberof Validator.validMethods886 * @param {regexp=} regexp 自定义验证正则表达式887 * @return {boolean} 验证结果888 * @desc 检测是否为合法身份证号码,可以自定义验证正则表达式889 * */890 , idNumber: function( regexp ){891 return (regexp || /^\d{6}(?:((?:19|20)\d{2})(?:0[1-9]|1[0-2])(?:0[1-9]|[1-2]\d|3[0-1])\d{3}(?:x|X|\d)|(?:\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[1-2]\d|3[0-1])\d{3}))$/).test( this.val() );892 }893 /**894 * @method fileType895 * @memberof Validator.validMethods896 * @param {string=} type 参数至少为 1 个 为文件类型后缀名 不包含点897 * @return {boolean} 验证结果898 * @desc 检测上传文件是否为合法类型899 * */900 , fileType: function(type){901 var result902 , argc = arguments.length903 , i = 0904 , regexp905 , val = this.val()906 ;907 if( this.is(':file') ){908 if( argc < 1 ){909 log('参数设置错误');910 result = false;911 }912 else{913 for(; i < argc; i++){914 if( !result ) break;915 regexp = new Regexp('\.'+ arguments[i] +'$', i);916 result = result && regexp.test( val );917 }918 }919 }920 else{921 log('标签错误');922 result = false;923 }924 return result;925 }926 /**927 * @method tel928 * @memberof Validator.validMethods929 * @return {boolean} 验证结果930 * @desc 验证是否为电话号码931 * @todo 待完成932 * */933 , tel: function(){934 var result = false;935 // todo 验证电话号码936 return result;937 }938 /**939 * @method phone940 * @memberof Validator.validMethods941 * @return {boolean} 验证结果942 * @desc 验证是否为手机号码943 * @todo 待完成944 * */945 , phone: function(){946 var result = false;947 // todo 验证手机号码948 return result;949 }950 };951 $.validator = Validator;952 return Validator;...

Full Screen

Full Screen

commonlib.js

Source:commonlib.js Github

copy

Full Screen

1/* IMPORTANT2 * =========3 * This script is included in the head section of every page.4 * This file should be kept small to not affect page load too bad.5 */6const validMethods = ['GET', 'POST'];7// Synchronous ajax requests...8// Asynchronous should be preferred.9// method = 'GET' or 'POST', url should be address pointing to localhost.10// Returns the ajax responseText or throws an Error.11function ajax(method, url) {12 // Function Guards13 if (!validMethods.includes(method)) {14 alert(`Unexpected request method: ${method.toString()}\nExpected one of: ${validMethods.toString()}`);15 throw new Error(`Unexpected request method: ${method.toString()}\nExpected one of: ${validMethods.toString()}`);16 }17 let ajaxRequest = new XMLHttpRequest();18 if (!ajaxRequest) {19 alert('Failed to create XMLHttpRequest (AJAX) instance!');20 throw new Error('Failed to create XMLHttpRequest (AJAX) instance!');21 }22 ajaxRequest.open(method, url, false);23 ajaxRequest.send();24 if (ajaxRequest.status === 200) {25 return ajaxRequest.responseText;26 } else {27 alert('Got non-200 (OK) HTTP status code in response.');28 throw new Error('Got non-200 (OK) HTTP status code in response.');29 }30}31/* Asynchronous via promises.32 * Returns a promise that contains the response text of the ajax request.33 */34function asyncAjax(method, url) {35 // Function Guards36 if (!validMethods.includes(method)) {37 return Promise.reject(`Unexpected request method: ${method.toString()}\nExpected one of: ${validMethods.toString()}`);38 }39 let promise = new Promise((resolve, reject) => {40 let ajaxRequest = new XMLHttpRequest();41 if (!ajaxRequest) {42 reject('Failed to create XMLHttpRequest (AJAX) instance!');43 }44 ajaxRequest.onreadystatechange = function() {45 // XMLHttpRequest.DONE === 446 if (ajaxRequest.readyState === 4) {47 if (ajaxRequest.status !== 200) {48 reject('Got non-200 (OK) HTTP status code in response.');49 } else {50 resolve(ajaxRequest.responseText);51 }52 }53 };54 ajaxRequest.open(method, url, true);55 ajaxRequest.send();56 });57 return promise;58}59window.onload = function() {60 console.log('hello');61 $('#dt').DataTable(62 {63 paging: false,64 searching: true,65 info: false66 }67 );68 document.querySelector('#dt_wrapper>div').style = 'min-width: 100%; margin-bottom: 5px;';69 document.querySelector('#dt_wrapper>div>div').style = 'max-width: 0%;';70 document.querySelector('#dt_wrapper').classList.add('justify-content-center');...

Full Screen

Full Screen

validMethods.js

Source:validMethods.js Github

copy

Full Screen

1/**2 * @description Middleware que verifica si el método usado es válido para un URI.3 * Si no es válido, devuelve una respuesta 405 personalizada4 * 5 * @param validMethods Arreglo que contiene los métodos válidos.6 */7const validMethods = (validMethods = ["GET", "HEAD"]) => (req, res, next) => {8 if (validMethods.includes(req.method)){9 return next();10 }11 12 res.status(405);13 res.set("Allow",validMethods.join(", "));14 res.header("Content-Type", "application/problem+json");15 res.json({16 title: "Method not allowed",17 detail: `The method ${req.method} is not allowed for this resource`,18 status: 40519 });20};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('API_KEY');3test.validMethods(function(err, data) {4 if (err) {5 console.log('error: ' + err);6 } else {7 console.log(data);8 }9});10var wpt = require('webpagetest');11var test = wpt('API_KEY');12test.validLocations(function(err, data) {13 if (err) {14 console.log('error: ' + err);15 } else {16 console.log(data);17 }18});19var wpt = require('webpagetest');20var test = wpt('API_KEY');21test.validPrivateLocations(function(err, data) {22 if (err) {23 console.log('error: ' + err);24 } else {25 console.log(data);26 }27});28var wpt = require('webpagetest');29var test = wpt('API_KEY');30test.validConnectivity(function(err, data) {31 if (err) {32 console.log('error: ' + err);33 } else {34 console.log(data);35 }36});37var wpt = require('webpagetest');38var test = wpt('API_KEY');39test.validBrowsers(function(err, data) {40 if (err) {41 console.log('error: ' + err);42 } else {43 console.log(data);44 }45});46var wpt = require('webpagetest');47var test = wpt('API_KEY');48test.validTestOptions(function(err, data) {49 if (err) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var validMethods = require('webpagetest');2validMethods(function(err, methods) {3 console.log(methods);4});5var validLocations = require('webpagetest');6validLocations(function(err, locations) {7 console.log(locations);8});9var validConnectivity = require('webpagetest');10validConnectivity(function(err, connectivity) {11 console.log(connectivity);12});13var validBrowsers = require('webpagetest');14validBrowsers(function(err, browsers) {15 console.log(browsers);16});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful