jquery.validate.js 43 KB

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