jquery.validate.js 51 KB

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