jquery.validate.js 42 KB

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