jquery.validate.js 50 KB

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