validate.js 44 KB

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