jquery.validate.js 47 KB

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