prometheus-net
1601 строка · 47.5 Кб
1/*!
2* jQuery Validation Plugin v1.17.0
3*
4* https://jqueryvalidation.org/
5*
6* Copyright (c) 2017 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}70function handle() {71var hidden, result;72
73// Insert a hidden input as a replacement for the missing submit button74// The hidden input is inserted in two cases:75// - A user defined a `submitHandler`76// - There was a pending request due to `remote` method and `stopRequest()`77// was called to submit the form in case it's valid78if ( validator.submitButton && ( validator.settings.submitHandler || validator.formSubmitted ) ) {79hidden = $( "<input type='hidden'/>" )80.attr( "name", validator.submitButton.name )81.val( $( validator.submitButton ).val() )82.appendTo( validator.currentForm );83}84
85if ( validator.settings.submitHandler ) {86result = validator.settings.submitHandler.call( validator, validator.currentForm, event );87if ( hidden ) {88
89// And clean up afterwards; thanks to no-block-scope, hidden can be referenced90hidden.remove();91}92if ( result !== undefined ) {93return result;94}95return false;96}97return true;98}99
100// Prevent submit for invalid forms or custom submit handlers101if ( validator.cancelSubmit ) {102validator.cancelSubmit = false;103return handle();104}105if ( validator.form() ) {106if ( validator.pendingRequest ) {107validator.formSubmitted = true;108return false;109}110return handle();111} else {112validator.focusInvalid();113return false;114}115} );116}117
118return validator;119},120
121// https://jqueryvalidation.org/valid/122valid: function() {123var valid, validator, errorList;124
125if ( $( this[ 0 ] ).is( "form" ) ) {126valid = this.validate().form();127} else {128errorList = [];129valid = true;130validator = $( this[ 0 ].form ).validate();131this.each( function() {132valid = validator.element( this ) && valid;133if ( !valid ) {134errorList = errorList.concat( validator.errorList );135}136} );137validator.errorList = errorList;138}139return valid;140},141
142// https://jqueryvalidation.org/rules/143rules: function( command, argument ) {144var element = this[ 0 ],145settings, staticRules, existingRules, data, param, filtered;146
147// If nothing is selected, return empty object; can't chain anyway148if ( element == null ) {149return;150}151
152if ( !element.form && element.hasAttribute( "contenteditable" ) ) {153element.form = this.closest( "form" )[ 0 ];154element.name = this.attr( "name" );155}156
157if ( element.form == null ) {158return;159}160
161if ( command ) {162settings = $.data( element.form, "validator" ).settings;163staticRules = settings.rules;164existingRules = $.validator.staticRules( element );165switch ( command ) {166case "add":167$.extend( existingRules, $.validator.normalizeRule( argument ) );168
169// Remove messages from rules, but allow them to be set separately170delete existingRules.messages;171staticRules[ element.name ] = existingRules;172if ( argument.messages ) {173settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );174}175break;176case "remove":177if ( !argument ) {178delete staticRules[ element.name ];179return existingRules;180}181filtered = {};182$.each( argument.split( /\s/ ), function( index, method ) {183filtered[ method ] = existingRules[ method ];184delete existingRules[ method ];185} );186return filtered;187}188}189
190data = $.validator.normalizeRules(191$.extend(192{},193$.validator.classRules( element ),194$.validator.attributeRules( element ),195$.validator.dataRules( element ),196$.validator.staticRules( element )197), element );198
199// Make sure required is at front200if ( data.required ) {201param = data.required;202delete data.required;203data = $.extend( { required: param }, data );204}205
206// Make sure remote is at back207if ( data.remote ) {208param = data.remote;209delete data.remote;210data = $.extend( data, { remote: param } );211}212
213return data;214}215} );216
217// Custom selectors
218$.extend( $.expr.pseudos || $.expr[ ":" ], { // '|| $.expr[ ":" ]' here enables backwards compatibility to jQuery 1.7. Can be removed when dropping jQ 1.7.x support219
220// https://jqueryvalidation.org/blank-selector/221blank: function( a ) {222return !$.trim( "" + $( a ).val() );223},224
225// https://jqueryvalidation.org/filled-selector/226filled: function( a ) {227var val = $( a ).val();228return val !== null && !!$.trim( "" + val );229},230
231// https://jqueryvalidation.org/unchecked-selector/232unchecked: function( a ) {233return !$( a ).prop( "checked" );234}235} );236
237// Constructor for validator
238$.validator = function( options, form ) {239this.settings = $.extend( true, {}, $.validator.defaults, options );240this.currentForm = form;241this.init();242};243
244// https://jqueryvalidation.org/jQuery.validator.format/
245$.validator.format = function( source, params ) {246if ( arguments.length === 1 ) {247return function() {248var args = $.makeArray( arguments );249args.unshift( source );250return $.validator.format.apply( this, args );251};252}253if ( params === undefined ) {254return source;255}256if ( arguments.length > 2 && params.constructor !== Array ) {257params = $.makeArray( arguments ).slice( 1 );258}259if ( params.constructor !== Array ) {260params = [ params ];261}262$.each( params, function( i, n ) {263source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() {264return n;265} );266} );267return source;268};269
270$.extend( $.validator, {271
272defaults: {273messages: {},274groups: {},275rules: {},276errorClass: "error",277pendingClass: "pending",278validClass: "valid",279errorElement: "label",280focusCleanup: false,281focusInvalid: true,282errorContainer: $( [] ),283errorLabelContainer: $( [] ),284onsubmit: true,285ignore: ":hidden",286ignoreTitle: false,287onfocusin: function( element ) {288this.lastActive = element;289
290// Hide error label and remove error class on focus if enabled291if ( this.settings.focusCleanup ) {292if ( this.settings.unhighlight ) {293this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );294}295this.hideThese( this.errorsFor( element ) );296}297},298onfocusout: function( element ) {299if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) {300this.element( element );301}302},303onkeyup: function( element, event ) {304
305// Avoid revalidate the field when pressing one of the following keys306// Shift => 16307// Ctrl => 17308// Alt => 18309// Caps lock => 20310// End => 35311// Home => 36312// Left arrow => 37313// Up arrow => 38314// Right arrow => 39315// Down arrow => 40316// Insert => 45317// Num lock => 144318// AltGr key => 225319var excludedKeys = [32016, 17, 18, 20, 35, 36, 37,32138, 39, 40, 45, 144, 225322];323
324if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {325return;326} else if ( element.name in this.submitted || element.name in this.invalid ) {327this.element( element );328}329},330onclick: function( element ) {331
332// Click on selects, radiobuttons and checkboxes333if ( element.name in this.submitted ) {334this.element( element );335
336// Or option elements, check parent select in that case337} else if ( element.parentNode.name in this.submitted ) {338this.element( element.parentNode );339}340},341highlight: function( element, errorClass, validClass ) {342if ( element.type === "radio" ) {343this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );344} else {345$( element ).addClass( errorClass ).removeClass( validClass );346}347},348unhighlight: function( element, errorClass, validClass ) {349if ( element.type === "radio" ) {350this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );351} else {352$( element ).removeClass( errorClass ).addClass( validClass );353}354}355},356
357// https://jqueryvalidation.org/jQuery.validator.setDefaults/358setDefaults: function( settings ) {359$.extend( $.validator.defaults, settings );360},361
362messages: {363required: "This field is required.",364remote: "Please fix this field.",365email: "Please enter a valid email address.",366url: "Please enter a valid URL.",367date: "Please enter a valid date.",368dateISO: "Please enter a valid date (ISO).",369number: "Please enter a valid number.",370digits: "Please enter only digits.",371equalTo: "Please enter the same value again.",372maxlength: $.validator.format( "Please enter no more than {0} characters." ),373minlength: $.validator.format( "Please enter at least {0} characters." ),374rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),375range: $.validator.format( "Please enter a value between {0} and {1}." ),376max: $.validator.format( "Please enter a value less than or equal to {0}." ),377min: $.validator.format( "Please enter a value greater than or equal to {0}." ),378step: $.validator.format( "Please enter a multiple of {0}." )379},380
381autoCreateRanges: false,382
383prototype: {384
385init: function() {386this.labelContainer = $( this.settings.errorLabelContainer );387this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );388this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );389this.submitted = {};390this.valueCache = {};391this.pendingRequest = 0;392this.pending = {};393this.invalid = {};394this.reset();395
396var groups = ( this.groups = {} ),397rules;398$.each( this.settings.groups, function( key, value ) {399if ( typeof value === "string" ) {400value = value.split( /\s/ );401}402$.each( value, function( index, name ) {403groups[ name ] = key;404} );405} );406rules = this.settings.rules;407$.each( rules, function( key, value ) {408rules[ key ] = $.validator.normalizeRule( value );409} );410
411function delegate( event ) {412
413// Set form expando on contenteditable414if ( !this.form && this.hasAttribute( "contenteditable" ) ) {415this.form = $( this ).closest( "form" )[ 0 ];416this.name = $( this ).attr( "name" );417}418
419var validator = $.data( this.form, "validator" ),420eventType = "on" + event.type.replace( /^validate/, "" ),421settings = validator.settings;422if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {423settings[ eventType ].call( validator, this, event );424}425}426
427$( this.currentForm )428.on( "focusin.validate focusout.validate keyup.validate",429":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +430"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +431"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +432"[type='radio'], [type='checkbox'], [contenteditable], [type='button']", delegate )433
434// Support: Chrome, oldIE435// "select" is provided as event.target when clicking a option436.on( "click.validate", "select, option, [type='radio'], [type='checkbox']", delegate );437
438if ( this.settings.invalidHandler ) {439$( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler );440}441},442
443// https://jqueryvalidation.org/Validator.form/444form: function() {445this.checkForm();446$.extend( this.submitted, this.errorMap );447this.invalid = $.extend( {}, this.errorMap );448if ( !this.valid() ) {449$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );450}451this.showErrors();452return this.valid();453},454
455checkForm: function() {456this.prepareForm();457for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {458this.check( elements[ i ] );459}460return this.valid();461},462
463// https://jqueryvalidation.org/Validator.element/464element: function( element ) {465var cleanElement = this.clean( element ),466checkElement = this.validationTargetFor( cleanElement ),467v = this,468result = true,469rs, group;470
471if ( checkElement === undefined ) {472delete this.invalid[ cleanElement.name ];473} else {474this.prepareElement( checkElement );475this.currentElements = $( checkElement );476
477// If this element is grouped, then validate all group elements already478// containing a value479group = this.groups[ checkElement.name ];480if ( group ) {481$.each( this.groups, function( name, testgroup ) {482if ( testgroup === group && name !== checkElement.name ) {483cleanElement = v.validationTargetFor( v.clean( v.findByName( name ) ) );484if ( cleanElement && cleanElement.name in v.invalid ) {485v.currentElements.push( cleanElement );486result = v.check( cleanElement ) && result;487}488}489} );490}491
492rs = this.check( checkElement ) !== false;493result = result && rs;494if ( rs ) {495this.invalid[ checkElement.name ] = false;496} else {497this.invalid[ checkElement.name ] = true;498}499
500if ( !this.numberOfInvalids() ) {501
502// Hide error containers on last error503this.toHide = this.toHide.add( this.containers );504}505this.showErrors();506
507// Add aria-invalid status for screen readers508$( element ).attr( "aria-invalid", !rs );509}510
511return result;512},513
514// https://jqueryvalidation.org/Validator.showErrors/515showErrors: function( errors ) {516if ( errors ) {517var validator = this;518
519// Add items to error list and map520$.extend( this.errorMap, errors );521this.errorList = $.map( this.errorMap, function( message, name ) {522return {523message: message,524element: validator.findByName( name )[ 0 ]525};526} );527
528// Remove items from success list529this.successList = $.grep( this.successList, function( element ) {530return !( element.name in errors );531} );532}533if ( this.settings.showErrors ) {534this.settings.showErrors.call( this, this.errorMap, this.errorList );535} else {536this.defaultShowErrors();537}538},539
540// https://jqueryvalidation.org/Validator.resetForm/541resetForm: function() {542if ( $.fn.resetForm ) {543$( this.currentForm ).resetForm();544}545this.invalid = {};546this.submitted = {};547this.prepareForm();548this.hideErrors();549var elements = this.elements()550.removeData( "previousValue" )551.removeAttr( "aria-invalid" );552
553this.resetElements( elements );554},555
556resetElements: function( elements ) {557var i;558
559if ( this.settings.unhighlight ) {560for ( i = 0; elements[ i ]; i++ ) {561this.settings.unhighlight.call( this, elements[ i ],562this.settings.errorClass, "" );563this.findByName( elements[ i ].name ).removeClass( this.settings.validClass );564}565} else {566elements
567.removeClass( this.settings.errorClass )568.removeClass( this.settings.validClass );569}570},571
572numberOfInvalids: function() {573return this.objectLength( this.invalid );574},575
576objectLength: function( obj ) {577/* jshint unused: false */578var count = 0,579i;580for ( i in obj ) {581
582// This check allows counting elements with empty error583// message as invalid elements584if ( obj[ i ] !== undefined && obj[ i ] !== null && obj[ i ] !== false ) {585count++;586}587}588return count;589},590
591hideErrors: function() {592this.hideThese( this.toHide );593},594
595hideThese: function( errors ) {596errors.not( this.containers ).text( "" );597this.addWrapper( errors ).hide();598},599
600valid: function() {601return this.size() === 0;602},603
604size: function() {605return this.errorList.length;606},607
608focusInvalid: function() {609if ( this.settings.focusInvalid ) {610try {611$( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [] )612.filter( ":visible" )613.focus()614
615// Manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find616.trigger( "focusin" );617} catch ( e ) {618
619// Ignore IE throwing errors when focusing hidden elements620}621}622},623
624findLastActive: function() {625var lastActive = this.lastActive;626return lastActive && $.grep( this.errorList, function( n ) {627return n.element.name === lastActive.name;628} ).length === 1 && lastActive;629},630
631elements: function() {632var validator = this,633rulesCache = {};634
635// Select all valid inputs inside the form (no submit or reset buttons)636return $( this.currentForm )637.find( "input, select, textarea, [contenteditable]" )638.not( ":submit, :reset, :image, :disabled" )639.not( this.settings.ignore )640.filter( function() {641var name = this.name || $( this ).attr( "name" ); // For contenteditable642if ( !name && validator.settings.debug && window.console ) {643console.error( "%o has no name assigned", this );644}645
646// Set form expando on contenteditable647if ( this.hasAttribute( "contenteditable" ) ) {648this.form = $( this ).closest( "form" )[ 0 ];649this.name = name;650}651
652// Select only the first element for each name, and only those with rules specified653if ( name in rulesCache || !validator.objectLength( $( this ).rules() ) ) {654return false;655}656
657rulesCache[ name ] = true;658return true;659} );660},661
662clean: function( selector ) {663return $( selector )[ 0 ];664},665
666errors: function() {667var errorClass = this.settings.errorClass.split( " " ).join( "." );668return $( this.settings.errorElement + "." + errorClass, this.errorContext );669},670
671resetInternals: function() {672this.successList = [];673this.errorList = [];674this.errorMap = {};675this.toShow = $( [] );676this.toHide = $( [] );677},678
679reset: function() {680this.resetInternals();681this.currentElements = $( [] );682},683
684prepareForm: function() {685this.reset();686this.toHide = this.errors().add( this.containers );687},688
689prepareElement: function( element ) {690this.reset();691this.toHide = this.errorsFor( element );692},693
694elementValue: function( element ) {695var $element = $( element ),696type = element.type,697val, idx;698
699if ( type === "radio" || type === "checkbox" ) {700return this.findByName( element.name ).filter( ":checked" ).val();701} else if ( type === "number" && typeof element.validity !== "undefined" ) {702return element.validity.badInput ? "NaN" : $element.val();703}704
705if ( element.hasAttribute( "contenteditable" ) ) {706val = $element.text();707} else {708val = $element.val();709}710
711if ( type === "file" ) {712
713// Modern browser (chrome & safari)714if ( val.substr( 0, 12 ) === "C:\\fakepath\\" ) {715return val.substr( 12 );716}717
718// Legacy browsers719// Unix-based path720idx = val.lastIndexOf( "/" );721if ( idx >= 0 ) {722return val.substr( idx + 1 );723}724
725// Windows-based path726idx = val.lastIndexOf( "\\" );727if ( idx >= 0 ) {728return val.substr( idx + 1 );729}730
731// Just the file name732return val;733}734
735if ( typeof val === "string" ) {736return val.replace( /\r/g, "" );737}738return val;739},740
741check: function( element ) {742element = this.validationTargetFor( this.clean( element ) );743
744var rules = $( element ).rules(),745rulesCount = $.map( rules, function( n, i ) {746return i;747} ).length,748dependencyMismatch = false,749val = this.elementValue( element ),750result, method, rule, normalizer;751
752// Prioritize the local normalizer defined for this element over the global one753// if the former exists, otherwise user the global one in case it exists.754if ( typeof rules.normalizer === "function" ) {755normalizer = rules.normalizer;756} else if ( typeof this.settings.normalizer === "function" ) {757normalizer = this.settings.normalizer;758}759
760// If normalizer is defined, then call it to retreive the changed value instead761// of using the real one.762// Note that `this` in the normalizer is `element`.763if ( normalizer ) {764val = normalizer.call( element, val );765
766if ( typeof val !== "string" ) {767throw new TypeError( "The normalizer should return a string value." );768}769
770// Delete the normalizer from rules to avoid treating it as a pre-defined method.771delete rules.normalizer;772}773
774for ( method in rules ) {775rule = { method: method, parameters: rules[ method ] };776try {777result = $.validator.methods[ method ].call( this, val, element, rule.parameters );778
779// If a method indicates that the field is optional and therefore valid,780// don't mark it as valid when there are no other rules781if ( result === "dependency-mismatch" && rulesCount === 1 ) {782dependencyMismatch = true;783continue;784}785dependencyMismatch = false;786
787if ( result === "pending" ) {788this.toHide = this.toHide.not( this.errorsFor( element ) );789return;790}791
792if ( !result ) {793this.formatAndAdd( element, rule );794return false;795}796} catch ( e ) {797if ( this.settings.debug && window.console ) {798console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );799}800if ( e instanceof TypeError ) {801e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";802}803
804throw e;805}806}807if ( dependencyMismatch ) {808return;809}810if ( this.objectLength( rules ) ) {811this.successList.push( element );812}813return true;814},815
816// Return the custom message for the given element and validation method817// specified in the element's HTML5 data attribute818// return the generic message if present and no method specific message is present819customDataMessage: function( element, method ) {820return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() +821method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" );822},823
824// Return the custom message for the given element name and validation method825customMessage: function( name, method ) {826var m = this.settings.messages[ name ];827return m && ( m.constructor === String ? m : m[ method ] );828},829
830// Return the first defined argument, allowing empty strings831findDefined: function() {832for ( var i = 0; i < arguments.length; i++ ) {833if ( arguments[ i ] !== undefined ) {834return arguments[ i ];835}836}837return undefined;838},839
840// The second parameter 'rule' used to be a string, and extended to an object literal841// of the following form:842// rule = {843// method: "method name",844// parameters: "the given method parameters"845// }846//847// The old behavior still supported, kept to maintain backward compatibility with848// old code, and will be removed in the next major release.849defaultMessage: function( element, rule ) {850if ( typeof rule === "string" ) {851rule = { method: rule };852}853
854var message = this.findDefined(855this.customMessage( element.name, rule.method ),856this.customDataMessage( element, rule.method ),857
858// 'title' is never undefined, so handle empty string as undefined859!this.settings.ignoreTitle && element.title || undefined,860$.validator.messages[ rule.method ],861"<strong>Warning: No message defined for " + element.name + "</strong>"862),863theregex = /\$?\{(\d+)\}/g;864if ( typeof message === "function" ) {865message = message.call( this, rule.parameters, element );866} else if ( theregex.test( message ) ) {867message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters );868}869
870return message;871},872
873formatAndAdd: function( element, rule ) {874var message = this.defaultMessage( element, rule );875
876this.errorList.push( {877message: message,878element: element,879method: rule.method880} );881
882this.errorMap[ element.name ] = message;883this.submitted[ element.name ] = message;884},885
886addWrapper: function( toToggle ) {887if ( this.settings.wrapper ) {888toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );889}890return toToggle;891},892
893defaultShowErrors: function() {894var i, elements, error;895for ( i = 0; this.errorList[ i ]; i++ ) {896error = this.errorList[ i ];897if ( this.settings.highlight ) {898this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );899}900this.showLabel( error.element, error.message );901}902if ( this.errorList.length ) {903this.toShow = this.toShow.add( this.containers );904}905if ( this.settings.success ) {906for ( i = 0; this.successList[ i ]; i++ ) {907this.showLabel( this.successList[ i ] );908}909}910if ( this.settings.unhighlight ) {911for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) {912this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass );913}914}915this.toHide = this.toHide.not( this.toShow );916this.hideErrors();917this.addWrapper( this.toShow ).show();918},919
920validElements: function() {921return this.currentElements.not( this.invalidElements() );922},923
924invalidElements: function() {925return $( this.errorList ).map( function() {926return this.element;927} );928},929
930showLabel: function( element, message ) {931var place, group, errorID, v,932error = this.errorsFor( element ),933elementID = this.idOrName( element ),934describedBy = $( element ).attr( "aria-describedby" );935
936if ( error.length ) {937
938// Refresh error/success class939error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );940
941// Replace message on existing label942error.html( message );943} else {944
945// Create error element946error = $( "<" + this.settings.errorElement + ">" )947.attr( "id", elementID + "-error" )948.addClass( this.settings.errorClass )949.html( message || "" );950
951// Maintain reference to the element to be placed into the DOM952place = error;953if ( this.settings.wrapper ) {954
955// Make sure the element is visible, even in IE956// actually showing the wrapped element is handled elsewhere957place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent();958}959if ( this.labelContainer.length ) {960this.labelContainer.append( place );961} else if ( this.settings.errorPlacement ) {962this.settings.errorPlacement.call( this, place, $( element ) );963} else {964place.insertAfter( element );965}966
967// Link error back to the element968if ( error.is( "label" ) ) {969
970// If the error is a label, then associate using 'for'971error.attr( "for", elementID );972
973// If the element is not a child of an associated label, then it's necessary974// to explicitly apply aria-describedby975} else if ( error.parents( "label[for='" + this.escapeCssMeta( elementID ) + "']" ).length === 0 ) {976errorID = error.attr( "id" );977
978// Respect existing non-error aria-describedby979if ( !describedBy ) {980describedBy = errorID;981} else if ( !describedBy.match( new RegExp( "\\b" + this.escapeCssMeta( errorID ) + "\\b" ) ) ) {982
983// Add to end of list if not already present984describedBy += " " + errorID;985}986$( element ).attr( "aria-describedby", describedBy );987
988// If this element is grouped, then assign to all elements in the same group989group = this.groups[ element.name ];990if ( group ) {991v = this;992$.each( v.groups, function( name, testgroup ) {993if ( testgroup === group ) {994$( "[name='" + v.escapeCssMeta( name ) + "']", v.currentForm )995.attr( "aria-describedby", error.attr( "id" ) );996}997} );998}999}1000}1001if ( !message && this.settings.success ) {1002error.text( "" );1003if ( typeof this.settings.success === "string" ) {1004error.addClass( this.settings.success );1005} else {1006this.settings.success( error, element );1007}1008}1009this.toShow = this.toShow.add( error );1010},1011
1012errorsFor: function( element ) {1013var name = this.escapeCssMeta( this.idOrName( element ) ),1014describer = $( element ).attr( "aria-describedby" ),1015selector = "label[for='" + name + "'], label[for='" + name + "'] *";1016
1017// 'aria-describedby' should directly reference the error element1018if ( describer ) {1019selector = selector + ", #" + this.escapeCssMeta( describer )1020.replace( /\s+/g, ", #" );1021}1022
1023return this1024.errors()1025.filter( selector );1026},1027
1028// See https://api.jquery.com/category/selectors/, for CSS1029// meta-characters that should be escaped in order to be used with JQuery1030// as a literal part of a name/id or any selector.1031escapeCssMeta: function( string ) {1032return string.replace( /([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g, "\\$1" );1033},1034
1035idOrName: function( element ) {1036return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name );1037},1038
1039validationTargetFor: function( element ) {1040
1041// If radio/checkbox, validate first element in group instead1042if ( this.checkable( element ) ) {1043element = this.findByName( element.name );1044}1045
1046// Always apply ignore filter1047return $( element ).not( this.settings.ignore )[ 0 ];1048},1049
1050checkable: function( element ) {1051return ( /radio|checkbox/i ).test( element.type );1052},1053
1054findByName: function( name ) {1055return $( this.currentForm ).find( "[name='" + this.escapeCssMeta( name ) + "']" );1056},1057
1058getLength: function( value, element ) {1059switch ( element.nodeName.toLowerCase() ) {1060case "select":1061return $( "option:selected", element ).length;1062case "input":1063if ( this.checkable( element ) ) {1064return this.findByName( element.name ).filter( ":checked" ).length;1065}1066}1067return value.length;1068},1069
1070depend: function( param, element ) {1071return this.dependTypes[ typeof param ] ? this.dependTypes[ typeof param ]( param, element ) : true;1072},1073
1074dependTypes: {1075"boolean": function( param ) {1076return param;1077},1078"string": function( param, element ) {1079return !!$( param, element.form ).length;1080},1081"function": function( param, element ) {1082return param( element );1083}1084},1085
1086optional: function( element ) {1087var val = this.elementValue( element );1088return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";1089},1090
1091startRequest: function( element ) {1092if ( !this.pending[ element.name ] ) {1093this.pendingRequest++;1094$( element ).addClass( this.settings.pendingClass );1095this.pending[ element.name ] = true;1096}1097},1098
1099stopRequest: function( element, valid ) {1100this.pendingRequest--;1101
1102// Sometimes synchronization fails, make sure pendingRequest is never < 01103if ( this.pendingRequest < 0 ) {1104this.pendingRequest = 0;1105}1106delete this.pending[ element.name ];1107$( element ).removeClass( this.settings.pendingClass );1108if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {1109$( this.currentForm ).submit();1110
1111// Remove the hidden input that was used as a replacement for the1112// missing submit button. The hidden input is added by `handle()`1113// to ensure that the value of the used submit button is passed on1114// for scripted submits triggered by this method1115if ( this.submitButton ) {1116$( "input:hidden[name='" + this.submitButton.name + "']", this.currentForm ).remove();1117}1118
1119this.formSubmitted = false;1120} else if ( !valid && this.pendingRequest === 0 && this.formSubmitted ) {1121$( this.currentForm ).triggerHandler( "invalid-form", [ this ] );1122this.formSubmitted = false;1123}1124},1125
1126previousValue: function( element, method ) {1127method = typeof method === "string" && method || "remote";1128
1129return $.data( element, "previousValue" ) || $.data( element, "previousValue", {1130old: null,1131valid: true,1132message: this.defaultMessage( element, { method: method } )1133} );1134},1135
1136// Cleans up all forms and elements, removes validator-specific events1137destroy: function() {1138this.resetForm();1139
1140$( this.currentForm )1141.off( ".validate" )1142.removeData( "validator" )1143.find( ".validate-equalTo-blur" )1144.off( ".validate-equalTo" )1145.removeClass( "validate-equalTo-blur" );1146}1147
1148},1149
1150classRuleSettings: {1151required: { required: true },1152email: { email: true },1153url: { url: true },1154date: { date: true },1155dateISO: { dateISO: true },1156number: { number: true },1157digits: { digits: true },1158creditcard: { creditcard: true }1159},1160
1161addClassRules: function( className, rules ) {1162if ( className.constructor === String ) {1163this.classRuleSettings[ className ] = rules;1164} else {1165$.extend( this.classRuleSettings, className );1166}1167},1168
1169classRules: function( element ) {1170var rules = {},1171classes = $( element ).attr( "class" );1172
1173if ( classes ) {1174$.each( classes.split( " " ), function() {1175if ( this in $.validator.classRuleSettings ) {1176$.extend( rules, $.validator.classRuleSettings[ this ] );1177}1178} );1179}1180return rules;1181},1182
1183normalizeAttributeRule: function( rules, type, method, value ) {1184
1185// Convert the value to a number for number inputs, and for text for backwards compability1186// allows type="date" and others to be compared as strings1187if ( /min|max|step/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {1188value = Number( value );1189
1190// Support Opera Mini, which returns NaN for undefined minlength1191if ( isNaN( value ) ) {1192value = undefined;1193}1194}1195
1196if ( value || value === 0 ) {1197rules[ method ] = value;1198} else if ( type === method && type !== "range" ) {1199
1200// Exception: the jquery validate 'range' method1201// does not test for the html5 'range' type1202rules[ method ] = true;1203}1204},1205
1206attributeRules: function( element ) {1207var rules = {},1208$element = $( element ),1209type = element.getAttribute( "type" ),1210method, value;1211
1212for ( method in $.validator.methods ) {1213
1214// Support for <input required> in both html5 and older browsers1215if ( method === "required" ) {1216value = element.getAttribute( method );1217
1218// Some browsers return an empty string for the required attribute1219// and non-HTML5 browsers might have required="" markup1220if ( value === "" ) {1221value = true;1222}1223
1224// Force non-HTML5 browsers to return bool1225value = !!value;1226} else {1227value = $element.attr( method );1228}1229
1230this.normalizeAttributeRule( rules, type, method, value );1231}1232
1233// 'maxlength' may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs1234if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) {1235delete rules.maxlength;1236}1237
1238return rules;1239},1240
1241dataRules: function( element ) {1242var rules = {},1243$element = $( element ),1244type = element.getAttribute( "type" ),1245method, value;1246
1247for ( method in $.validator.methods ) {1248value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );1249this.normalizeAttributeRule( rules, type, method, value );1250}1251return rules;1252},1253
1254staticRules: function( element ) {1255var rules = {},1256validator = $.data( element.form, "validator" );1257
1258if ( validator.settings.rules ) {1259rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {};1260}1261return rules;1262},1263
1264normalizeRules: function( rules, element ) {1265
1266// Handle dependency check1267$.each( rules, function( prop, val ) {1268
1269// Ignore rule when param is explicitly false, eg. required:false1270if ( val === false ) {1271delete rules[ prop ];1272return;1273}1274if ( val.param || val.depends ) {1275var keepRule = true;1276switch ( typeof val.depends ) {1277case "string":1278keepRule = !!$( val.depends, element.form ).length;1279break;1280case "function":1281keepRule = val.depends.call( element, element );1282break;1283}1284if ( keepRule ) {1285rules[ prop ] = val.param !== undefined ? val.param : true;1286} else {1287$.data( element.form, "validator" ).resetElements( $( element ) );1288delete rules[ prop ];1289}1290}1291} );1292
1293// Evaluate parameters1294$.each( rules, function( rule, parameter ) {1295rules[ rule ] = $.isFunction( parameter ) && rule !== "normalizer" ? parameter( element ) : parameter;1296} );1297
1298// Clean number parameters1299$.each( [ "minlength", "maxlength" ], function() {1300if ( rules[ this ] ) {1301rules[ this ] = Number( rules[ this ] );1302}1303} );1304$.each( [ "rangelength", "range" ], function() {1305var parts;1306if ( rules[ this ] ) {1307if ( $.isArray( rules[ this ] ) ) {1308rules[ this ] = [ Number( rules[ this ][ 0 ] ), Number( rules[ this ][ 1 ] ) ];1309} else if ( typeof rules[ this ] === "string" ) {1310parts = rules[ this ].replace( /[\[\]]/g, "" ).split( /[\s,]+/ );1311rules[ this ] = [ Number( parts[ 0 ] ), Number( parts[ 1 ] ) ];1312}1313}1314} );1315
1316if ( $.validator.autoCreateRanges ) {1317
1318// Auto-create ranges1319if ( rules.min != null && rules.max != null ) {1320rules.range = [ rules.min, rules.max ];1321delete rules.min;1322delete rules.max;1323}1324if ( rules.minlength != null && rules.maxlength != null ) {1325rules.rangelength = [ rules.minlength, rules.maxlength ];1326delete rules.minlength;1327delete rules.maxlength;1328}1329}1330
1331return rules;1332},1333
1334// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}1335normalizeRule: function( data ) {1336if ( typeof data === "string" ) {1337var transformed = {};1338$.each( data.split( /\s/ ), function() {1339transformed[ this ] = true;1340} );1341data = transformed;1342}1343return data;1344},1345
1346// https://jqueryvalidation.org/jQuery.validator.addMethod/1347addMethod: function( name, method, message ) {1348$.validator.methods[ name ] = method;1349$.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ];1350if ( method.length < 3 ) {1351$.validator.addClassRules( name, $.validator.normalizeRule( name ) );1352}1353},1354
1355// https://jqueryvalidation.org/jQuery.validator.methods/1356methods: {1357
1358// https://jqueryvalidation.org/required-method/1359required: function( value, element, param ) {1360
1361// Check if dependency is met1362if ( !this.depend( param, element ) ) {1363return "dependency-mismatch";1364}1365if ( element.nodeName.toLowerCase() === "select" ) {1366
1367// Could be an array for select-multiple or a string, both are fine this way1368var val = $( element ).val();1369return val && val.length > 0;1370}1371if ( this.checkable( element ) ) {1372return this.getLength( value, element ) > 0;1373}1374return value.length > 0;1375},1376
1377// https://jqueryvalidation.org/email-method/1378email: function( value, element ) {1379
1380// From https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address1381// Retrieved 2014-01-141382// If you have a problem with this implementation, report a bug against the above spec1383// Or use custom methods to implement your own email validation1384return 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 );1385},1386
1387// https://jqueryvalidation.org/url-method/1388url: function( value, element ) {1389
1390// Copyright (c) 2010-2013 Diego Perini, MIT licensed1391// https://gist.github.com/dperini/7292941392// see also https://mathiasbynens.be/demo/url-regex1393// modified to allow protocol-relative URLs1394return 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-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );1395},1396
1397// https://jqueryvalidation.org/date-method/1398date: function( value, element ) {1399return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );1400},1401
1402// https://jqueryvalidation.org/dateISO-method/1403dateISO: function( value, element ) {1404return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value );1405},1406
1407// https://jqueryvalidation.org/number-method/1408number: function( value, element ) {1409return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );1410},1411
1412// https://jqueryvalidation.org/digits-method/1413digits: function( value, element ) {1414return this.optional( element ) || /^\d+$/.test( value );1415},1416
1417// https://jqueryvalidation.org/minlength-method/1418minlength: function( value, element, param ) {1419var length = $.isArray( value ) ? value.length : this.getLength( value, element );1420return this.optional( element ) || length >= param;1421},1422
1423// https://jqueryvalidation.org/maxlength-method/1424maxlength: function( value, element, param ) {1425var length = $.isArray( value ) ? value.length : this.getLength( value, element );1426return this.optional( element ) || length <= param;1427},1428
1429// https://jqueryvalidation.org/rangelength-method/1430rangelength: function( value, element, param ) {1431var length = $.isArray( value ) ? value.length : this.getLength( value, element );1432return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] );1433},1434
1435// https://jqueryvalidation.org/min-method/1436min: function( value, element, param ) {1437return this.optional( element ) || value >= param;1438},1439
1440// https://jqueryvalidation.org/max-method/1441max: function( value, element, param ) {1442return this.optional( element ) || value <= param;1443},1444
1445// https://jqueryvalidation.org/range-method/1446range: function( value, element, param ) {1447return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] );1448},1449
1450// https://jqueryvalidation.org/step-method/1451step: function( value, element, param ) {1452var type = $( element ).attr( "type" ),1453errorMessage = "Step attribute on input type " + type + " is not supported.",1454supportedTypes = [ "text", "number", "range" ],1455re = new RegExp( "\\b" + type + "\\b" ),1456notSupported = type && !re.test( supportedTypes.join() ),1457decimalPlaces = function( num ) {1458var match = ( "" + num ).match( /(?:\.(\d+))?$/ );1459if ( !match ) {1460return 0;1461}1462
1463// Number of digits right of decimal point.1464return match[ 1 ] ? match[ 1 ].length : 0;1465},1466toInt = function( num ) {1467return Math.round( num * Math.pow( 10, decimals ) );1468},1469valid = true,1470decimals;1471
1472// Works only for text, number and range input types1473// TODO find a way to support input types date, datetime, datetime-local, month, time and week1474if ( notSupported ) {1475throw new Error( errorMessage );1476}1477
1478decimals = decimalPlaces( param );1479
1480// Value can't have too many decimals1481if ( decimalPlaces( value ) > decimals || toInt( value ) % toInt( param ) !== 0 ) {1482valid = false;1483}1484
1485return this.optional( element ) || valid;1486},1487
1488// https://jqueryvalidation.org/equalTo-method/1489equalTo: function( value, element, param ) {1490
1491// Bind to the blur event of the target in order to revalidate whenever the target field is updated1492var target = $( param );1493if ( this.settings.onfocusout && target.not( ".validate-equalTo-blur" ).length ) {1494target.addClass( "validate-equalTo-blur" ).on( "blur.validate-equalTo", function() {1495$( element ).valid();1496} );1497}1498return value === target.val();1499},1500
1501// https://jqueryvalidation.org/remote-method/1502remote: function( value, element, param, method ) {1503if ( this.optional( element ) ) {1504return "dependency-mismatch";1505}1506
1507method = typeof method === "string" && method || "remote";1508
1509var previous = this.previousValue( element, method ),1510validator, data, optionDataString;1511
1512if ( !this.settings.messages[ element.name ] ) {1513this.settings.messages[ element.name ] = {};1514}1515previous.originalMessage = previous.originalMessage || this.settings.messages[ element.name ][ method ];1516this.settings.messages[ element.name ][ method ] = previous.message;1517
1518param = typeof param === "string" && { url: param } || param;1519optionDataString = $.param( $.extend( { data: value }, param.data ) );1520if ( previous.old === optionDataString ) {1521return previous.valid;1522}1523
1524previous.old = optionDataString;1525validator = this;1526this.startRequest( element );1527data = {};1528data[ element.name ] = value;1529$.ajax( $.extend( true, {1530mode: "abort",1531port: "validate" + element.name,1532dataType: "json",1533data: data,1534context: validator.currentForm,1535success: function( response ) {1536var valid = response === true || response === "true",1537errors, message, submitted;1538
1539validator.settings.messages[ element.name ][ method ] = previous.originalMessage;1540if ( valid ) {1541submitted = validator.formSubmitted;1542validator.resetInternals();1543validator.toHide = validator.errorsFor( element );1544validator.formSubmitted = submitted;1545validator.successList.push( element );1546validator.invalid[ element.name ] = false;1547validator.showErrors();1548} else {1549errors = {};1550message = response || validator.defaultMessage( element, { method: method, parameters: value } );1551errors[ element.name ] = previous.message = message;1552validator.invalid[ element.name ] = true;1553validator.showErrors( errors );1554}1555previous.valid = valid;1556validator.stopRequest( element, valid );1557}1558}, param ) );1559return "pending";1560}1561}1562
1563} );1564
1565// Ajax mode: abort
1566// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
1567// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
1568
1569var pendingRequests = {},1570ajax;1571
1572// Use a prefilter if available (1.5+)
1573if ( $.ajaxPrefilter ) {1574$.ajaxPrefilter( function( settings, _, xhr ) {1575var port = settings.port;1576if ( settings.mode === "abort" ) {1577if ( pendingRequests[ port ] ) {1578pendingRequests[ port ].abort();1579}1580pendingRequests[ port ] = xhr;1581}1582} );1583} else {1584
1585// Proxy ajax1586ajax = $.ajax;1587$.ajax = function( settings ) {1588var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,1589port = ( "port" in settings ? settings : $.ajaxSettings ).port;1590if ( mode === "abort" ) {1591if ( pendingRequests[ port ] ) {1592pendingRequests[ port ].abort();1593}1594pendingRequests[ port ] = ajax.apply( this, arguments );1595return pendingRequests[ port ];1596}1597return ajax.apply( this, arguments );1598};1599}
1600return $;1601}));