jquery.validate.js 50 KB

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