GPQAPP
1657 строк · 49.8 Кб
1/*!
2* jQuery Validation Plugin v1.19.3
3*
4* https://jqueryvalidation.org/
5*
6* Copyright (c) 2021 Jörn Zaefferer
7* Released under the MIT license
8*/
9(function( factory ) {10if ( typeof define === "function" && define.amd ) {11define( ["jquery"], factory );12} else if (typeof module === "object" && module.exports) {13module.exports = factory( require( "jquery" ) );14} else {15factory( jQuery );16}17}(function( $ ) {18
19$.extend( $.fn, {20
21// https://jqueryvalidation.org/validate/22validate: function( options ) {23
24// If nothing is selected, return nothing; can't chain anyway25if ( !this.length ) {26if ( options && options.debug && window.console ) {27console.warn( "Nothing selected, can't validate, returning nothing." );28}29return;30}31
32// Check if a validator for this form was already created33var validator = $.data( this[ 0 ], "validator" );34if ( validator ) {35return validator;36}37
38// Add novalidate tag if HTML5.39this.attr( "novalidate", "novalidate" );40
41validator = new $.validator( options, this[ 0 ] );42$.data( this[ 0 ], "validator", validator );43
44if ( validator.settings.onsubmit ) {45
46this.on( "click.validate", ":submit", function( event ) {47
48// Track the used submit button to properly handle scripted49// submits later.50validator.submitButton = event.currentTarget;51
52// Allow suppressing validation by adding a cancel class to the submit button53if ( $( this ).hasClass( "cancel" ) ) {54validator.cancelSubmit = true;55}56
57// Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button58if ( $( this ).attr( "formnovalidate" ) !== undefined ) {59validator.cancelSubmit = true;60}61} );62
63// Validate the form on submit64this.on( "submit.validate", function( event ) {65if ( validator.settings.debug ) {66
67// Prevent form submit to be able to see console output68event.preventDefault();69}70
71function handle() {72var hidden, result;73
74// Insert a hidden input as a replacement for the missing submit button75// The hidden input is inserted in two cases:76// - A user defined a `submitHandler`77// - There was a pending request due to `remote` method and `stopRequest()`78// was called to submit the form in case it's valid79if ( validator.submitButton && ( validator.settings.submitHandler || validator.formSubmitted ) ) {80hidden = $( "<input type='hidden'/>" )81.attr( "name", validator.submitButton.name )82.val( $( validator.submitButton ).val() )83.appendTo( validator.currentForm );84}85
86if ( validator.settings.submitHandler && !validator.settings.debug ) {87result = validator.settings.submitHandler.call( validator, validator.currentForm, event );88if ( hidden ) {89
90// And clean up afterwards; thanks to no-block-scope, hidden can be referenced91hidden.remove();92}93if ( result !== undefined ) {94return result;95}96return false;97}98return true;99}100
101// Prevent submit for invalid forms or custom submit handlers102if ( validator.cancelSubmit ) {103validator.cancelSubmit = false;104return handle();105}106if ( validator.form() ) {107if ( validator.pendingRequest ) {108validator.formSubmitted = true;109return false;110}111return handle();112} else {113validator.focusInvalid();114return false;115}116} );117}118
119return validator;120},121
122// https://jqueryvalidation.org/valid/123valid: function() {124var valid, validator, errorList;125
126if ( $( this[ 0 ] ).is( "form" ) ) {127valid = this.validate().form();128} else {129errorList = [];130valid = true;131validator = $( this[ 0 ].form ).validate();132this.each( function() {133valid = validator.element( this ) && valid;134if ( !valid ) {135errorList = errorList.concat( validator.errorList );136}137} );138validator.errorList = errorList;139}140return valid;141},142
143// https://jqueryvalidation.org/rules/144rules: function( command, argument ) {145var element = this[ 0 ],146isContentEditable = typeof this.attr( "contenteditable" ) !== "undefined" && this.attr( "contenteditable" ) !== "false",147settings, staticRules, existingRules, data, param, filtered;148
149// If nothing is selected, return empty object; can't chain anyway150if ( element == null ) {151return;152}153
154if ( !element.form && isContentEditable ) {155element.form = this.closest( "form" )[ 0 ];156element.name = this.attr( "name" );157}158
159if ( element.form == null ) {160return;161}162
163if ( command ) {164settings = $.data( element.form, "validator" ).settings;165staticRules = settings.rules;166existingRules = $.validator.staticRules( element );167switch ( command ) {168case "add":169$.extend( existingRules, $.validator.normalizeRule( argument ) );170
171// Remove messages from rules, but allow them to be set separately172delete existingRules.messages;173staticRules[ element.name ] = existingRules;174if ( argument.messages ) {175settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );176}177break;178case "remove":179if ( !argument ) {180delete staticRules[ element.name ];181return existingRules;182}183filtered = {};184$.each( argument.split( /\s/ ), function( index, method ) {185filtered[ method ] = existingRules[ method ];186delete existingRules[ method ];187} );188return filtered;189}190}191
192data = $.validator.normalizeRules(193$.extend(194{},195$.validator.classRules( element ),196$.validator.attributeRules( element ),197$.validator.dataRules( element ),198$.validator.staticRules( element )199), element );200
201// Make sure required is at front202if ( data.required ) {203param = data.required;204delete data.required;205data = $.extend( { required: param }, data );206}207
208// Make sure remote is at back209if ( data.remote ) {210param = data.remote;211delete data.remote;212data = $.extend( data, { remote: param } );213}214
215return data;216}217} );218
219// JQuery trim is deprecated, provide a trim method based on String.prototype.trim
220var trim = function( str ) {221
222// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Polyfill223return str.replace( /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "" );224};225
226// Custom selectors
227$.extend( $.expr.pseudos || $.expr[ ":" ], { // '|| $.expr[ ":" ]' here enables backwards compatibility to jQuery 1.7. Can be removed when dropping jQ 1.7.x support228
229// https://jqueryvalidation.org/blank-selector/230blank: function( a ) {231return !trim( "" + $( a ).val() );232},233
234// https://jqueryvalidation.org/filled-selector/235filled: function( a ) {236var val = $( a ).val();237return val !== null && !!trim( "" + val );238},239
240// https://jqueryvalidation.org/unchecked-selector/241unchecked: function( a ) {242return !$( a ).prop( "checked" );243}244} );245
246// Constructor for validator
247$.validator = function( options, form ) {248this.settings = $.extend( true, {}, $.validator.defaults, options );249this.currentForm = form;250this.init();251};252
253// https://jqueryvalidation.org/jQuery.validator.format/
254$.validator.format = function( source, params ) {255if ( arguments.length === 1 ) {256return function() {257var args = $.makeArray( arguments );258args.unshift( source );259return $.validator.format.apply( this, args );260};261}262if ( params === undefined ) {263return source;264}265if ( arguments.length > 2 && params.constructor !== Array ) {266params = $.makeArray( arguments ).slice( 1 );267}268if ( params.constructor !== Array ) {269params = [ params ];270}271$.each( params, function( i, n ) {272source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {273return n;274} );275} );276return source;277};278
279$.extend( $.validator, {280
281defaults: {282messages: {},283groups: {},284rules: {},285errorClass: "error",286pendingClass: "pending",287validClass: "valid",288errorElement: "label",289focusCleanup: false,290focusInvalid: true,291errorContainer: $( [] ),292errorLabelContainer: $( [] ),293onsubmit: true,294ignore: ":hidden",295ignoreTitle: false,296onfocusin: function( element ) {297this.lastActive = element;298
299// Hide error label and remove error class on focus if enabled300if ( this.settings.focusCleanup ) {301if ( this.settings.unhighlight ) {302this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );303}304this.hideThese( this.errorsFor( element ) );305}306},307onfocusout: function( element ) {308if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) {309this.element( element );310}311},312onkeyup: function( element, event ) {313
314// Avoid revalidate the field when pressing one of the following keys315// Shift => 16316// Ctrl => 17317// Alt => 18318// Caps lock => 20319// End => 35320// Home => 36321// Left arrow => 37322// Up arrow => 38323// Right arrow => 39324// Down arrow => 40325// Insert => 45326// Num lock => 144327// AltGr key => 225328var excludedKeys = [32916, 17, 18, 20, 35, 36, 37,33038, 39, 40, 45, 144, 225331];332
333if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {334return;335} else if ( element.name in this.submitted || element.name in this.invalid ) {336this.element( element );337}338},339onclick: function( element ) {340
341// Click on selects, radiobuttons and checkboxes342if ( element.name in this.submitted ) {343this.element( element );344
345// Or option elements, check parent select in that case346} else if ( element.parentNode.name in this.submitted ) {347this.element( element.parentNode );348}349},350highlight: function( element, errorClass, validClass ) {351if ( element.type === "radio" ) {352this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );353} else {354$( element ).addClass( errorClass ).removeClass( validClass );355}356},357unhighlight: function( element, errorClass, validClass ) {358if ( element.type === "radio" ) {359this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );360} else {361$( element ).removeClass( errorClass ).addClass( validClass );362}363}364},365
366// https://jqueryvalidation.org/jQuery.validator.setDefaults/367setDefaults: function( settings ) {368$.extend( $.validator.defaults, settings );369},370
371messages: {372required: "This field is required.",373remote: "Please fix this field.",374email: "Please enter a valid email address.",375url: "Please enter a valid URL.",376date: "Please enter a valid date.",377dateISO: "Please enter a valid date (ISO).",378number: "Please enter a valid number.",379digits: "Please enter only digits.",380equalTo: "Please enter the same value again.",381maxlength: $.validator.format( "Please enter no more than {0} characters." ),382minlength: $.validator.format( "Please enter at least {0} characters." ),383rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),384range: $.validator.format( "Please enter a value between {0} and {1}." ),385max: $.validator.format( "Please enter a value less than or equal to {0}." ),386min: $.validator.format( "Please enter a value greater than or equal to {0}." ),387step: $.validator.format( "Please enter a multiple of {0}." )388},389
390autoCreateRanges: false,391
392prototype: {393
394init: function() {395this.labelContainer = $( this.settings.errorLabelContainer );396this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );397this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );398this.submitted = {};399this.valueCache = {};400this.pendingRequest = 0;401this.pending = {};402this.invalid = {};403this.reset();404
405var currentForm = this.currentForm,406groups = ( this.groups = {} ),407rules;408$.each( this.settings.groups, function( key, value ) {409if ( typeof value === "string" ) {410value = value.split( /\s/ );411}412$.each( value, function( index, name ) {413groups[ name ] = key;414} );415} );416rules = this.settings.rules;417$.each( rules, function( key, value ) {418rules[ key ] = $.validator.normalizeRule( value );419} );420
421function delegate( event ) {422var isContentEditable = typeof $( this ).attr( "contenteditable" ) !== "undefined" && $( this ).attr( "contenteditable" ) !== "false";423
424// Set form expando on contenteditable425if ( !this.form && isContentEditable ) {426this.form = $( this ).closest( "form" )[ 0 ];427this.name = $( this ).attr( "name" );428}429
430// Ignore the element if it belongs to another form. This will happen mainly431// when setting the `form` attribute of an input to the id of another form.432if ( currentForm !== this.form ) {433return;434}435
436var validator = $.data( this.form, "validator" ),437eventType = "on" + event.type.replace( /^validate/, "" ),438settings = validator.settings;439if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {440settings[ eventType ].call( validator, this, event );441}442}443
444$( this.currentForm )445.on( "focusin.validate focusout.validate keyup.validate",446":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +447"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +448"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +449"[type='radio'], [type='checkbox'], [contenteditable], [type='button']", delegate )450
451// Support: Chrome, oldIE452// "select" is provided as event.target when clicking a option453.on( "click.validate", "select, option, [type='radio'], [type='checkbox']", delegate );454
455if ( this.settings.invalidHandler ) {456$( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler );457}458},459
460// https://jqueryvalidation.org/Validator.form/461form: function() {462this.checkForm();463$.extend( this.submitted, this.errorMap );464this.invalid = $.extend( {}, this.errorMap );465if ( !this.valid() ) {466$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );467}468this.showErrors();469return this.valid();470},471
472checkForm: function() {473this.prepareForm();474for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {475this.check( elements[ i ] );476}477return this.valid();478},479
480// https://jqueryvalidation.org/Validator.element/481element: function( element ) {482var cleanElement = this.clean( element ),483checkElement = this.validationTargetFor( cleanElement ),484v = this,485result = true,486rs, group;487
488if ( checkElement === undefined ) {489delete this.invalid[ cleanElement.name ];490} else {491this.prepareElement( checkElement );492this.currentElements = $( checkElement );493
494// If this element is grouped, then validate all group elements already495// containing a value496group = this.groups[ checkElement.name ];497if ( group ) {498$.each( this.groups, function( name, testgroup ) {499if ( testgroup === group && name !== checkElement.name ) {500cleanElement = v.validationTargetFor( v.clean( v.findByName( name ) ) );501if ( cleanElement && cleanElement.name in v.invalid ) {502v.currentElements.push( cleanElement );503result = v.check( cleanElement ) && result;504}505}506} );507}508
509rs = this.check( checkElement ) !== false;510result = result && rs;511if ( rs ) {512this.invalid[ checkElement.name ] = false;513} else {514this.invalid[ checkElement.name ] = true;515}516
517if ( !this.numberOfInvalids() ) {518
519// Hide error containers on last error520this.toHide = this.toHide.add( this.containers );521}522this.showErrors();523
524// Add aria-invalid status for screen readers525$( element ).attr( "aria-invalid", !rs );526}527
528return result;529},530
531// https://jqueryvalidation.org/Validator.showErrors/532showErrors: function( errors ) {533if ( errors ) {534var validator = this;535
536// Add items to error list and map537$.extend( this.errorMap, errors );538this.errorList = $.map( this.errorMap, function( message, name ) {539return {540message: message,541element: validator.findByName( name )[ 0 ]542};543} );544
545// Remove items from success list546this.successList = $.grep( this.successList, function( element ) {547return !( element.name in errors );548} );549}550if ( this.settings.showErrors ) {551this.settings.showErrors.call( this, this.errorMap, this.errorList );552} else {553this.defaultShowErrors();554}555},556
557// https://jqueryvalidation.org/Validator.resetForm/558resetForm: function() {559if ( $.fn.resetForm ) {560$( this.currentForm ).resetForm();561}562this.invalid = {};563this.submitted = {};564this.prepareForm();565this.hideErrors();566var elements = this.elements()567.removeData( "previousValue" )568.removeAttr( "aria-invalid" );569
570this.resetElements( elements );571},572
573resetElements: function( elements ) {574var i;575
576if ( this.settings.unhighlight ) {577for ( i = 0; elements[ i ]; i++ ) {578this.settings.unhighlight.call( this, elements[ i ],579this.settings.errorClass, "" );580this.findByName( elements[ i ].name ).removeClass( this.settings.validClass );581}582} else {583elements
584.removeClass( this.settings.errorClass )585.removeClass( this.settings.validClass );586}587},588
589numberOfInvalids: function() {590return this.objectLength( this.invalid );591},592
593objectLength: function( obj ) {594/* jshint unused: false */595var count = 0,596i;597for ( i in obj ) {598
599// This check allows counting elements with empty error600// message as invalid elements601if ( obj[ i ] !== undefined && obj[ i ] !== null && obj[ i ] !== false ) {602count++;603}604}605return count;606},607
608hideErrors: function() {609this.hideThese( this.toHide );610},611
612hideThese: function( errors ) {613errors.not( this.containers ).text( "" );614this.addWrapper( errors ).hide();615},616
617valid: function() {618return this.size() === 0;619},620
621size: function() {622return this.errorList.length;623},624
625focusInvalid: function() {626if ( this.settings.focusInvalid ) {627try {628$( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [] )629.filter( ":visible" )630.trigger( "focus" )631
632// Manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find633.trigger( "focusin" );634} catch ( e ) {635
636// Ignore IE throwing errors when focusing hidden elements637}638}639},640
641findLastActive: function() {642var lastActive = this.lastActive;643return lastActive && $.grep( this.errorList, function( n ) {644return n.element.name === lastActive.name;645} ).length === 1 && lastActive;646},647
648elements: function() {649var validator = this,650rulesCache = {};651
652// Select all valid inputs inside the form (no submit or reset buttons)653return $( this.currentForm )654.find( "input, select, textarea, [contenteditable]" )655.not( ":submit, :reset, :image, :disabled" )656.not( this.settings.ignore )657.filter( function() {658var name = this.name || $( this ).attr( "name" ); // For contenteditable659var isContentEditable = typeof $( this ).attr( "contenteditable" ) !== "undefined" && $( this ).attr( "contenteditable" ) !== "false";660
661if ( !name && validator.settings.debug && window.console ) {662console.error( "%o has no name assigned", this );663}664
665// Set form expando on contenteditable666if ( isContentEditable ) {667this.form = $( this ).closest( "form" )[ 0 ];668this.name = name;669}670
671// Ignore elements that belong to other/nested forms672if ( this.form !== validator.currentForm ) {673return false;674}675
676// Select only the first element for each name, and only those with rules specified677if ( name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {678return false;679}680
681rulesCache[ name ] = true;682return true;683} );684},685
686clean: function( selector ) {687return $( selector )[ 0 ];688},689
690errors: function() {691var errorClass = this.settings.errorClass.split( " " ).join( "." );692return $( this.settings.errorElement + "." + errorClass, this.errorContext );693},694
695resetInternals: function() {696this.successList = [];697this.errorList = [];698this.errorMap = {};699this.toShow = $( [] );700this.toHide = $( [] );701},702
703reset: function() {704this.resetInternals();705this.currentElements = $( [] );706},707
708prepareForm: function() {709this.reset();710this.toHide = this.errors().add( this.containers );711},712
713prepareElement: function( element ) {714this.reset();715this.toHide = this.errorsFor( element );716},717
718elementValue: function( element ) {719var $element = $( element ),720type = element.type,721isContentEditable = typeof $element.attr( "contenteditable" ) !== "undefined" && $element.attr( "contenteditable" ) !== "false",722val, idx;723
724if ( type === "radio" || type === "checkbox" ) {725return this.findByName( element.name ).filter( ":checked" ).val();726} else if ( type === "number" && typeof element.validity !== "undefined" ) {727return element.validity.badInput ? "NaN" : $element.val();728}729
730if ( isContentEditable ) {731val = $element.text();732} else {733val = $element.val();734}735
736if ( type === "file" ) {737
738// Modern browser (chrome & safari)739if ( val.substr( 0, 12 ) === "C:\\fakepath\\" ) {740return val.substr( 12 );741}742
743// Legacy browsers744// Unix-based path745idx = val.lastIndexOf( "/" );746if ( idx >= 0 ) {747return val.substr( idx + 1 );748}749
750// Windows-based path751idx = val.lastIndexOf( "\\" );752if ( idx >= 0 ) {753return val.substr( idx + 1 );754}755
756// Just the file name757return val;758}759
760if ( typeof val === "string" ) {761return val.replace( /\r/g, "" );762}763return val;764},765
766check: function( element ) {767element = this.validationTargetFor( this.clean( element ) );768
769var rules = $( element ).rules(),770rulesCount = $.map( rules, function( n, i ) {771return i;772} ).length,773dependencyMismatch = false,774val = this.elementValue( element ),775result, method, rule, normalizer;776
777// Prioritize the local normalizer defined for this element over the global one778// if the former exists, otherwise user the global one in case it exists.779if ( typeof rules.normalizer === "function" ) {780normalizer = rules.normalizer;781} else if ( typeof this.settings.normalizer === "function" ) {782normalizer = this.settings.normalizer;783}784
785// If normalizer is defined, then call it to retreive the changed value instead786// of using the real one.787// Note that `this` in the normalizer is `element`.788if ( normalizer ) {789val = normalizer.call( element, val );790
791// Delete the normalizer from rules to avoid treating it as a pre-defined method.792delete rules.normalizer;793}794
795for ( method in rules ) {796rule = { method: method, parameters: rules[ method ] };797try {798result = $.validator.methods[ method ].call( this, val, element, rule.parameters );799
800// If a method indicates that the field is optional and therefore valid,801// don't mark it as valid when there are no other rules802if ( result === "dependency-mismatch" && rulesCount === 1 ) {803dependencyMismatch = true;804continue;805}806dependencyMismatch = false;807
808if ( result === "pending" ) {809this.toHide = this.toHide.not( this.errorsFor( element ) );810return;811}812
813if ( !result ) {814this.formatAndAdd( element, rule );815return false;816}817} catch ( e ) {818if ( this.settings.debug && window.console ) {819console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );820}821if ( e instanceof TypeError ) {822e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";823}824
825throw e;826}827}828if ( dependencyMismatch ) {829return;830}831if ( this.objectLength( rules ) ) {832this.successList.push( element );833}834return true;835},836
837// Return the custom message for the given element and validation method838// specified in the element's HTML5 data attribute839// return the generic message if present and no method specific message is present840customDataMessage: function( element, method ) {841return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() +842method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" );843},844
845// Return the custom message for the given element name and validation method846customMessage: function( name, method ) {847var m = this.settings.messages[ name ];848return m && ( m.constructor === String ? m : m[ method ] );849},850
851// Return the first defined argument, allowing empty strings852findDefined: function() {853for ( var i = 0; i < arguments.length; i++ ) {854if ( arguments[ i ] !== undefined ) {855return arguments[ i ];856}857}858return undefined;859},860
861// The second parameter 'rule' used to be a string, and extended to an object literal862// of the following form:863// rule = {864// method: "method name",865// parameters: "the given method parameters"866// }867//868// The old behavior still supported, kept to maintain backward compatibility with869// old code, and will be removed in the next major release.870defaultMessage: function( element, rule ) {871if ( typeof rule === "string" ) {872rule = { method: rule };873}874
875var message = this.findDefined(876this.customMessage( element.name, rule.method ),877this.customDataMessage( element, rule.method ),878
879// 'title' is never undefined, so handle empty string as undefined880!this.settings.ignoreTitle && element.title || undefined,881$.validator.messages[ rule.method ],882"<strong>Warning: No message defined for " + element.name + "</strong>"883),884theregex = /\$?\{(\d+)\}/g;885if ( typeof message === "function" ) {886message = message.call( this, rule.parameters, element );887} else if ( theregex.test( message ) ) {888message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters );889}890
891return message;892},893
894formatAndAdd: function( element, rule ) {895var message = this.defaultMessage( element, rule );896
897this.errorList.push( {898message: message,899element: element,900method: rule.method901} );902
903this.errorMap[ element.name ] = message;904this.submitted[ element.name ] = message;905},906
907addWrapper: function( toToggle ) {908if ( this.settings.wrapper ) {909toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );910}911return toToggle;912},913
914defaultShowErrors: function() {915var i, elements, error;916for ( i = 0; this.errorList[ i ]; i++ ) {917error = this.errorList[ i ];918if ( this.settings.highlight ) {919this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );920}921this.showLabel( error.element, error.message );922}923if ( this.errorList.length ) {924this.toShow = this.toShow.add( this.containers );925}926if ( this.settings.success ) {927for ( i = 0; this.successList[ i ]; i++ ) {928this.showLabel( this.successList[ i ] );929}930}931if ( this.settings.unhighlight ) {932for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) {933this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass );934}935}936this.toHide = this.toHide.not( this.toShow );937this.hideErrors();938this.addWrapper( this.toShow ).show();939},940
941validElements: function() {942return this.currentElements.not( this.invalidElements() );943},944
945invalidElements: function() {946return $( this.errorList ).map( function() {947return this.element;948} );949},950
951showLabel: function( element, message ) {952var place, group, errorID, v,953error = this.errorsFor( element ),954elementID = this.idOrName( element ),955describedBy = $( element ).attr( "aria-describedby" );956
957if ( error.length ) {958
959// Refresh error/success class960error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );961
962// Replace message on existing label963error.html( message );964} else {965
966// Create error element967error = $( "<" + this.settings.errorElement + ">" )968.attr( "id", elementID + "-error" )969.addClass( this.settings.errorClass )970.html( message || "" );971
972// Maintain reference to the element to be placed into the DOM973place = error;974if ( this.settings.wrapper ) {975
976// Make sure the element is visible, even in IE977// actually showing the wrapped element is handled elsewhere978place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent();979}980if ( this.labelContainer.length ) {981this.labelContainer.append( place );982} else if ( this.settings.errorPlacement ) {983this.settings.errorPlacement.call( this, place, $( element ) );984} else {985place.insertAfter( element );986}987
988// Link error back to the element989if ( error.is( "label" ) ) {990
991// If the error is a label, then associate using 'for'992error.attr( "for", elementID );993
994// If the element is not a child of an associated label, then it's necessary995// to explicitly apply aria-describedby996} else if ( error.parents( "label[for='" + this.escapeCssMeta( elementID ) + "']" ).length === 0 ) {997errorID = error.attr( "id" );998
999// Respect existing non-error aria-describedby1000if ( !describedBy ) {1001describedBy = errorID;1002} else if ( !describedBy.match( new RegExp( "\\b" + this.escapeCssMeta( errorID ) + "\\b" ) ) ) {1003
1004// Add to end of list if not already present1005describedBy += " " + errorID;1006}1007$( element ).attr( "aria-describedby", describedBy );1008
1009// If this element is grouped, then assign to all elements in the same group1010group = this.groups[ element.name ];1011if ( group ) {1012v = this;1013$.each( v.groups, function( name, testgroup ) {1014if ( testgroup === group ) {1015$( "[name='" + v.escapeCssMeta( name ) + "']", v.currentForm )1016.attr( "aria-describedby", error.attr( "id" ) );1017}1018} );1019}1020}1021}1022if ( !message && this.settings.success ) {1023error.text( "" );1024if ( typeof this.settings.success === "string" ) {1025error.addClass( this.settings.success );1026} else {1027this.settings.success( error, element );1028}1029}1030this.toShow = this.toShow.add( error );1031},1032
1033errorsFor: function( element ) {1034var name = this.escapeCssMeta( this.idOrName( element ) ),1035describer = $( element ).attr( "aria-describedby" ),1036selector = "label[for='" + name + "'], label[for='" + name + "'] *";1037
1038// 'aria-describedby' should directly reference the error element1039if ( describer ) {1040selector = selector + ", #" + this.escapeCssMeta( describer )1041.replace( /\s+/g, ", #" );1042}1043
1044return this1045.errors()1046.filter( selector );1047},1048
1049// See https://api.jquery.com/category/selectors/, for CSS1050// meta-characters that should be escaped in order to be used with JQuery1051// as a literal part of a name/id or any selector.1052escapeCssMeta: function( string ) {1053return string.replace( /([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g, "\\$1" );1054},1055
1056idOrName: function( element ) {1057return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name );1058},1059
1060validationTargetFor: function( element ) {1061
1062// If radio/checkbox, validate first element in group instead1063if ( this.checkable( element ) ) {1064element = this.findByName( element.name );1065}1066
1067// Always apply ignore filter1068return $( element ).not( this.settings.ignore )[ 0 ];1069},1070
1071checkable: function( element ) {1072return ( /radio|checkbox/i ).test( element.type );1073},1074
1075findByName: function( name ) {1076return $( this.currentForm ).find( "[name='" + this.escapeCssMeta( name ) + "']" );1077},1078
1079getLength: function( value, element ) {1080switch ( element.nodeName.toLowerCase() ) {1081case "select":1082return $( "option:selected", element ).length;1083case "input":1084if ( this.checkable( element ) ) {1085return this.findByName( element.name ).filter( ":checked" ).length;1086}1087}1088return value.length;1089},1090
1091depend: function( param, element ) {1092return this.dependTypes[ typeof param ] ? this.dependTypes[ typeof param ]( param, element ) : true;1093},1094
1095dependTypes: {1096"boolean": function( param ) {1097return param;1098},1099"string": function( param, element ) {1100return !!$( param, element.form ).length;1101},1102"function": function( param, element ) {1103return param( element );1104}1105},1106
1107optional: function( element ) {1108var val = this.elementValue( element );1109return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";1110},1111
1112startRequest: function( element ) {1113if ( !this.pending[ element.name ] ) {1114this.pendingRequest++;1115$( element ).addClass( this.settings.pendingClass );1116this.pending[ element.name ] = true;1117}1118},1119
1120stopRequest: function( element, valid ) {1121this.pendingRequest--;1122
1123// Sometimes synchronization fails, make sure pendingRequest is never < 01124if ( this.pendingRequest < 0 ) {1125this.pendingRequest = 0;1126}1127delete this.pending[ element.name ];1128$( element ).removeClass( this.settings.pendingClass );1129if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {1130$( this.currentForm ).submit();1131
1132// Remove the hidden input that was used as a replacement for the1133// missing submit button. The hidden input is added by `handle()`1134// to ensure that the value of the used submit button is passed on1135// for scripted submits triggered by this method1136if ( this.submitButton ) {1137$( "input:hidden[name='" + this.submitButton.name + "']", this.currentForm ).remove();1138}1139
1140this.formSubmitted = false;1141} else if ( !valid && this.pendingRequest === 0 && this.formSubmitted ) {1142$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );1143this.formSubmitted = false;1144}1145},1146
1147previousValue: function( element, method ) {1148method = typeof method === "string" && method || "remote";1149
1150return $.data( element, "previousValue" ) || $.data( element, "previousValue", {1151old: null,1152valid: true,1153message: this.defaultMessage( element, { method: method } )1154} );1155},1156
1157// Cleans up all forms and elements, removes validator-specific events1158destroy: function() {1159this.resetForm();1160
1161$( this.currentForm )1162.off( ".validate" )1163.removeData( "validator" )1164.find( ".validate-equalTo-blur" )1165.off( ".validate-equalTo" )1166.removeClass( "validate-equalTo-blur" )1167.find( ".validate-lessThan-blur" )1168.off( ".validate-lessThan" )1169.removeClass( "validate-lessThan-blur" )1170.find( ".validate-lessThanEqual-blur" )1171.off( ".validate-lessThanEqual" )1172.removeClass( "validate-lessThanEqual-blur" )1173.find( ".validate-greaterThanEqual-blur" )1174.off( ".validate-greaterThanEqual" )1175.removeClass( "validate-greaterThanEqual-blur" )1176.find( ".validate-greaterThan-blur" )1177.off( ".validate-greaterThan" )1178.removeClass( "validate-greaterThan-blur" );1179}1180
1181},1182
1183classRuleSettings: {1184required: { required: true },1185email: { email: true },1186url: { url: true },1187date: { date: true },1188dateISO: { dateISO: true },1189number: { number: true },1190digits: { digits: true },1191creditcard: { creditcard: true }1192},1193
1194addClassRules: function( className, rules ) {1195if ( className.constructor === String ) {1196this.classRuleSettings[ className ] = rules;1197} else {1198$.extend( this.classRuleSettings, className );1199}1200},1201
1202classRules: function( element ) {1203var rules = {},1204classes = $( element ).attr( "class" );1205
1206if ( classes ) {1207$.each( classes.split( " " ), function() {1208if ( this in $.validator.classRuleSettings ) {1209$.extend( rules, $.validator.classRuleSettings[ this ] );1210}1211} );1212}1213return rules;1214},1215
1216normalizeAttributeRule: function( rules, type, method, value ) {1217
1218// Convert the value to a number for number inputs, and for text for backwards compability1219// allows type="date" and others to be compared as strings1220if ( /min|max|step/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {1221value = Number( value );1222
1223// Support Opera Mini, which returns NaN for undefined minlength1224if ( isNaN( value ) ) {1225value = undefined;1226}1227}1228
1229if ( value || value === 0 ) {1230rules[ method ] = value;1231} else if ( type === method && type !== "range" ) {1232
1233// Exception: the jquery validate 'range' method1234// does not test for the html5 'range' type1235rules[ method ] = true;1236}1237},1238
1239attributeRules: function( element ) {1240var rules = {},1241$element = $( element ),1242type = element.getAttribute( "type" ),1243method, value;1244
1245for ( method in $.validator.methods ) {1246
1247// Support for <input required> in both html5 and older browsers1248if ( method === "required" ) {1249value = element.getAttribute( method );1250
1251// Some browsers return an empty string for the required attribute1252// and non-HTML5 browsers might have required="" markup1253if ( value === "" ) {1254value = true;1255}1256
1257// Force non-HTML5 browsers to return bool1258value = !!value;1259} else {1260value = $element.attr( method );1261}1262
1263this.normalizeAttributeRule( rules, type, method, value );1264}1265
1266// 'maxlength' may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs1267if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) {1268delete rules.maxlength;1269}1270
1271return rules;1272},1273
1274dataRules: function( element ) {1275var rules = {},1276$element = $( element ),1277type = element.getAttribute( "type" ),1278method, value;1279
1280for ( method in $.validator.methods ) {1281value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );1282
1283// Cast empty attributes like `data-rule-required` to `true`1284if ( value === "" ) {1285value = true;1286}1287
1288this.normalizeAttributeRule( rules, type, method, value );1289}1290return rules;1291},1292
1293staticRules: function( element ) {1294var rules = {},1295validator = $.data( element.form, "validator" );1296
1297if ( validator.settings.rules ) {1298rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {};1299}1300return rules;1301},1302
1303normalizeRules: function( rules, element ) {1304
1305// Handle dependency check1306$.each( rules, function( prop, val ) {1307
1308// Ignore rule when param is explicitly false, eg. required:false1309if ( val === false ) {1310delete rules[ prop ];1311return;1312}1313if ( val.param || val.depends ) {1314var keepRule = true;1315switch ( typeof val.depends ) {1316case "string":1317keepRule = !!$( val.depends, element.form ).length;1318break;1319case "function":1320keepRule = val.depends.call( element, element );1321break;1322}1323if ( keepRule ) {1324rules[ prop ] = val.param !== undefined ? val.param : true;1325} else {1326$.data( element.form, "validator" ).resetElements( $( element ) );1327delete rules[ prop ];1328}1329}1330} );1331
1332// Evaluate parameters1333$.each( rules, function( rule, parameter ) {1334rules[ rule ] = typeof parameter === "function" && rule !== "normalizer" ? parameter( element ) : parameter;1335} );1336
1337// Clean number parameters1338$.each( [ "minlength", "maxlength" ], function() {1339if ( rules[ this ] ) {1340rules[ this ] = Number( rules[ this ] );1341}1342} );1343$.each( [ "rangelength", "range" ], function() {1344var parts;1345if ( rules[ this ] ) {1346if ( Array.isArray( rules[ this ] ) ) {1347rules[ this ] = [ Number( rules[ this ][ 0 ] ), Number( rules[ this ][ 1 ] ) ];1348} else if ( typeof rules[ this ] === "string" ) {1349parts = rules[ this ].replace( /[\[\]]/g, "" ).split( /[\s,]+/ );1350rules[ this ] = [ Number( parts[ 0 ] ), Number( parts[ 1 ] ) ];1351}1352}1353} );1354
1355if ( $.validator.autoCreateRanges ) {1356
1357// Auto-create ranges1358if ( rules.min != null && rules.max != null ) {1359rules.range = [ rules.min, rules.max ];1360delete rules.min;1361delete rules.max;1362}1363if ( rules.minlength != null && rules.maxlength != null ) {1364rules.rangelength = [ rules.minlength, rules.maxlength ];1365delete rules.minlength;1366delete rules.maxlength;1367}1368}1369
1370return rules;1371},1372
1373// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}1374normalizeRule: function( data ) {1375if ( typeof data === "string" ) {1376var transformed = {};1377$.each( data.split( /\s/ ), function() {1378transformed[ this ] = true;1379} );1380data = transformed;1381}1382return data;1383},1384
1385// https://jqueryvalidation.org/jQuery.validator.addMethod/1386addMethod: function( name, method, message ) {1387$.validator.methods[ name ] = method;1388$.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ];1389if ( method.length < 3 ) {1390$.validator.addClassRules( name, $.validator.normalizeRule( name ) );1391}1392},1393
1394// https://jqueryvalidation.org/jQuery.validator.methods/1395methods: {1396
1397// https://jqueryvalidation.org/required-method/1398required: function( value, element, param ) {1399
1400// Check if dependency is met1401if ( !this.depend( param, element ) ) {1402return "dependency-mismatch";1403}1404if ( element.nodeName.toLowerCase() === "select" ) {1405
1406// Could be an array for select-multiple or a string, both are fine this way1407var val = $( element ).val();1408return val && val.length > 0;1409}1410if ( this.checkable( element ) ) {1411return this.getLength( value, element ) > 0;1412}1413return value !== undefined && value !== null && value.length > 0;1414},1415
1416// https://jqueryvalidation.org/email-method/1417email: function( value, element ) {1418
1419// From https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address1420// Retrieved 2014-01-141421// If you have a problem with this implementation, report a bug against the above spec1422// Or use custom methods to implement your own email validation1423return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );1424},1425
1426// https://jqueryvalidation.org/url-method/1427url: function( value, element ) {1428
1429// Copyright (c) 2010-2013 Diego Perini, MIT licensed1430// https://gist.github.com/dperini/7292941431// see also https://mathiasbynens.be/demo/url-regex1432// modified to allow protocol-relative URLs1433return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );1434},1435
1436// https://jqueryvalidation.org/date-method/1437date: ( function() {1438var called = false;1439
1440return function( value, element ) {1441if ( !called ) {1442called = true;1443if ( this.settings.debug && window.console ) {1444console.warn(1445"The `date` method is deprecated and will be removed in version '2.0.0'.\n" +1446"Please don't use it, since it relies on the Date constructor, which\n" +1447"behaves very differently across browsers and locales. Use `dateISO`\n" +1448"instead or one of the locale specific methods in `localizations/`\n" +1449"and `additional-methods.js`."1450);1451}1452}1453
1454return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );1455};1456}() ),1457
1458// https://jqueryvalidation.org/dateISO-method/1459dateISO: function( value, element ) {1460return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value );1461},1462
1463// https://jqueryvalidation.org/number-method/1464number: function( value, element ) {1465return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );1466},1467
1468// https://jqueryvalidation.org/digits-method/1469digits: function( value, element ) {1470return this.optional( element ) || /^\d+$/.test( value );1471},1472
1473// https://jqueryvalidation.org/minlength-method/1474minlength: function( value, element, param ) {1475var length = Array.isArray( value ) ? value.length : this.getLength( value, element );1476return this.optional( element ) || length >= param;1477},1478
1479// https://jqueryvalidation.org/maxlength-method/1480maxlength: function( value, element, param ) {1481var length = Array.isArray( value ) ? value.length : this.getLength( value, element );1482return this.optional( element ) || length <= param;1483},1484
1485// https://jqueryvalidation.org/rangelength-method/1486rangelength: function( value, element, param ) {1487var length = Array.isArray( value ) ? value.length : this.getLength( value, element );1488return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] );1489},1490
1491// https://jqueryvalidation.org/min-method/1492min: function( value, element, param ) {1493return this.optional( element ) || value >= param;1494},1495
1496// https://jqueryvalidation.org/max-method/1497max: function( value, element, param ) {1498return this.optional( element ) || value <= param;1499},1500
1501// https://jqueryvalidation.org/range-method/1502range: function( value, element, param ) {1503return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );1504},1505
1506// https://jqueryvalidation.org/step-method/1507step: function( value, element, param ) {1508var type = $( element ).attr( "type" ),1509errorMessage = "Step attribute on input type " + type + " is not supported.",1510supportedTypes = [ "text", "number", "range" ],1511re = new RegExp( "\\b" + type + "\\b" ),1512notSupported = type && !re.test( supportedTypes.join() ),1513decimalPlaces = function( num ) {1514var match = ( "" + num ).match( /(?:\.(\d+))?$/ );1515if ( !match ) {1516return 0;1517}1518
1519// Number of digits right of decimal point.1520return match[ 1 ] ? match[ 1 ].length : 0;1521},1522toInt = function( num ) {1523return Math.round( num * Math.pow( 10, decimals ) );1524},1525valid = true,1526decimals;1527
1528// Works only for text, number and range input types1529// TODO find a way to support input types date, datetime, datetime-local, month, time and week1530if ( notSupported ) {1531throw new Error( errorMessage );1532}1533
1534decimals = decimalPlaces( param );1535
1536// Value can't have too many decimals1537if ( decimalPlaces( value ) > decimals || toInt( value ) % toInt( param ) !== 0 ) {1538valid = false;1539}1540
1541return this.optional( element ) || valid;1542},1543
1544// https://jqueryvalidation.org/equalTo-method/1545equalTo: function( value, element, param ) {1546
1547// Bind to the blur event of the target in order to revalidate whenever the target field is updated1548var target = $( param );1549if ( this.settings.onfocusout && target.not( ".validate-equalTo-blur" ).length ) {1550target.addClass( "validate-equalTo-blur" ).on( "blur.validate-equalTo", function() {1551$( element ).valid();1552} );1553}1554return value === target.val();1555},1556
1557// https://jqueryvalidation.org/remote-method/1558remote: function( value, element, param, method ) {1559if ( this.optional( element ) ) {1560return "dependency-mismatch";1561}1562
1563method = typeof method === "string" && method || "remote";1564
1565var previous = this.previousValue( element, method ),1566validator, data, optionDataString;1567
1568if ( !this.settings.messages[ element.name ] ) {1569this.settings.messages[ element.name ] = {};1570}1571previous.originalMessage = previous.originalMessage || this.settings.messages[ element.name ][ method ];1572this.settings.messages[ element.name ][ method ] = previous.message;1573
1574param = typeof param === "string" && { url: param } || param;1575optionDataString = $.param( $.extend( { data: value }, param.data ) );1576if ( previous.old === optionDataString ) {1577return previous.valid;1578}1579
1580previous.old = optionDataString;1581validator = this;1582this.startRequest( element );1583data = {};1584data[ element.name ] = value;1585$.ajax( $.extend( true, {1586mode: "abort",1587port: "validate" + element.name,1588dataType: "json",1589data: data,1590context: validator.currentForm,1591success: function( response ) {1592var valid = response === true || response === "true",1593errors, message, submitted;1594
1595validator.settings.messages[ element.name ][ method ] = previous.originalMessage;1596if ( valid ) {1597submitted = validator.formSubmitted;1598validator.resetInternals();1599validator.toHide = validator.errorsFor( element );1600validator.formSubmitted = submitted;1601validator.successList.push( element );1602validator.invalid[ element.name ] = false;1603validator.showErrors();1604} else {1605errors = {};1606message = response || validator.defaultMessage( element, { method: method, parameters: value } );1607errors[ element.name ] = previous.message = message;1608validator.invalid[ element.name ] = true;1609validator.showErrors( errors );1610}1611previous.valid = valid;1612validator.stopRequest( element, valid );1613}1614}, param ) );1615return "pending";1616}1617}1618
1619} );1620
1621// Ajax mode: abort
1622// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
1623// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
1624
1625var pendingRequests = {},1626ajax;1627
1628// Use a prefilter if available (1.5+)
1629if ( $.ajaxPrefilter ) {1630$.ajaxPrefilter( function( settings, _, xhr ) {1631var port = settings.port;1632if ( settings.mode === "abort" ) {1633if ( pendingRequests[ port ] ) {1634pendingRequests[ port ].abort();1635}1636pendingRequests[ port ] = xhr;1637}1638} );1639} else {1640
1641// Proxy ajax1642ajax = $.ajax;1643$.ajax = function( settings ) {1644var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,1645port = ( "port" in settings ? settings : $.ajaxSettings ).port;1646if ( mode === "abort" ) {1647if ( pendingRequests[ port ] ) {1648pendingRequests[ port ].abort();1649}1650pendingRequests[ port ] = ajax.apply( this, arguments );1651return pendingRequests[ port ];1652}1653return ajax.apply( this, arguments );1654};1655}
1656return $;1657}));