jquery.validate.js 48 KB

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