jquery.validate.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. /**
  2. * jQuery Validation Plugin 1.9.0
  3. *
  4. * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
  5. * http://docs.jquery.com/Plugins/Validation
  6. *
  7. * Copyright (c) 2006 - 2011 Jörn Zaefferer
  8. *
  9. * Licensed under MIT: http://www.opensource.org/licenses/mit-license.php
  10. */
  11. (function($) {
  12. $.extend($.fn, {
  13. // http://docs.jquery.com/Plugins/Validation/validate
  14. validate: function( options ) {
  15. // if nothing is selected, return nothing; can't chain anyway
  16. if (!this.length) {
  17. options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
  18. return;
  19. }
  20. // check if a validator for this form was already created
  21. var validator = $.data(this[0], 'validator');
  22. if ( validator ) {
  23. return validator;
  24. }
  25. // Add novalidate tag if HTML5.
  26. this.attr('novalidate', 'novalidate');
  27. validator = new $.validator( options, this[0] );
  28. $.data(this[0], 'validator', validator);
  29. if ( validator.settings.onsubmit ) {
  30. var inputsAndButtons = this.find("input, button");
  31. // allow suppresing validation by adding a cancel class to the submit button
  32. inputsAndButtons.filter(".cancel").click(function () {
  33. validator.cancelSubmit = true;
  34. });
  35. // when a submitHandler is used, capture the submitting button
  36. if (validator.settings.submitHandler) {
  37. inputsAndButtons.filter(":submit").click(function () {
  38. validator.submitButton = this;
  39. });
  40. }
  41. // validate the form on submit
  42. this.submit( function( event ) {
  43. if ( validator.settings.debug )
  44. // prevent form submit to be able to see console output
  45. event.preventDefault();
  46. function handle() {
  47. if ( validator.settings.submitHandler ) {
  48. if (validator.submitButton) {
  49. // insert a hidden input as a replacement for the missing submit button
  50. var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
  51. }
  52. validator.settings.submitHandler.call( validator, validator.currentForm );
  53. if (validator.submitButton) {
  54. // and clean up afterwards; thanks to no-block-scope, hidden can be referenced
  55. hidden.remove();
  56. }
  57. return false;
  58. }
  59. return true;
  60. }
  61. // prevent submit for invalid forms or custom submit handlers
  62. if ( validator.cancelSubmit ) {
  63. validator.cancelSubmit = false;
  64. return handle();
  65. }
  66. if ( validator.form() ) {
  67. if ( validator.pendingRequest ) {
  68. validator.formSubmitted = true;
  69. return false;
  70. }
  71. return handle();
  72. } else {
  73. validator.focusInvalid();
  74. return false;
  75. }
  76. });
  77. }
  78. return validator;
  79. },
  80. // http://docs.jquery.com/Plugins/Validation/valid
  81. valid: function() {
  82. if ( $(this[0]).is('form')) {
  83. return this.validate().form();
  84. } else {
  85. var valid = true;
  86. var validator = $(this[0].form).validate();
  87. this.each(function() {
  88. valid &= validator.element(this);
  89. });
  90. return valid;
  91. }
  92. },
  93. // attributes: space seperated list of attributes to retrieve and remove
  94. removeAttrs: function(attributes) {
  95. var result = {},
  96. $element = this;
  97. $.each(attributes.split(/\s/), function(index, value) {
  98. result[value] = $element.attr(value);
  99. $element.removeAttr(value);
  100. });
  101. return result;
  102. },
  103. // http://docs.jquery.com/Plugins/Validation/rules
  104. rules: function(command, argument) {
  105. var element = this[0];
  106. if (command) {
  107. var settings = $.data(element.form, 'validator').settings;
  108. var staticRules = settings.rules;
  109. var existingRules = $.validator.staticRules(element);
  110. switch(command) {
  111. case "add":
  112. $.extend(existingRules, $.validator.normalizeRule(argument));
  113. staticRules[element.name] = existingRules;
  114. if (argument.messages)
  115. settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
  116. break;
  117. case "remove":
  118. if (!argument) {
  119. delete staticRules[element.name];
  120. return existingRules;
  121. }
  122. var filtered = {};
  123. $.each(argument.split(/\s/), function(index, method) {
  124. filtered[method] = existingRules[method];
  125. delete existingRules[method];
  126. });
  127. return filtered;
  128. }
  129. }
  130. var data = $.validator.normalizeRules(
  131. $.extend(
  132. {},
  133. $.validator.metadataRules(element),
  134. $.validator.classRules(element),
  135. $.validator.attributeRules(element),
  136. $.validator.staticRules(element)
  137. ), element);
  138. // make sure required is at front
  139. if (data.required) {
  140. var param = data.required;
  141. delete data.required;
  142. data = $.extend({required: param}, data);
  143. }
  144. return data;
  145. }
  146. });
  147. // Custom selectors
  148. $.extend($.expr[":"], {
  149. // http://docs.jquery.com/Plugins/Validation/blank
  150. blank: function(a) {return !$.trim("" + a.value);},
  151. // http://docs.jquery.com/Plugins/Validation/filled
  152. filled: function(a) {return !!$.trim("" + a.value);},
  153. // http://docs.jquery.com/Plugins/Validation/unchecked
  154. unchecked: function(a) {return !a.checked;}
  155. });
  156. // constructor for validator
  157. $.validator = function( options, form ) {
  158. this.settings = $.extend( true, {}, $.validator.defaults, options );
  159. this.currentForm = form;
  160. this.init();
  161. };
  162. $.validator.format = function(source, params) {
  163. if ( arguments.length == 1 )
  164. return function() {
  165. var args = $.makeArray(arguments);
  166. args.unshift(source);
  167. return $.validator.format.apply( this, args );
  168. };
  169. if ( arguments.length > 2 && params.constructor != Array ) {
  170. params = $.makeArray(arguments).slice(1);
  171. }
  172. if ( params.constructor != Array ) {
  173. params = [ params ];
  174. }
  175. $.each(params, function(i, n) {
  176. source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
  177. });
  178. return source;
  179. };
  180. $.extend($.validator, {
  181. defaults: {
  182. messages: {},
  183. groups: {},
  184. rules: {},
  185. errorClass: "error",
  186. validClass: "valid",
  187. errorElement: "label",
  188. focusInvalid: true,
  189. errorContainer: $( [] ),
  190. errorLabelContainer: $( [] ),
  191. onsubmit: true,
  192. ignore: ":hidden",
  193. ignoreTitle: false,
  194. onfocusin: function(element, event) {
  195. this.lastActive = element;
  196. // hide error label and remove error class on focus if enabled
  197. if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
  198. this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
  199. this.addWrapper(this.errorsFor(element)).hide();
  200. }
  201. },
  202. onfocusout: function(element, event) {
  203. if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
  204. this.element(element);
  205. }
  206. },
  207. onkeyup: function(element, event) {
  208. if ( element.name in this.submitted || element == this.lastElement ) {
  209. this.element(element);
  210. }
  211. },
  212. onclick: function(element, event) {
  213. // click on selects, radiobuttons and checkboxes
  214. if ( element.name in this.submitted )
  215. this.element(element);
  216. // or option elements, check parent select in that case
  217. else if (element.parentNode.name in this.submitted)
  218. this.element(element.parentNode);
  219. },
  220. highlight: function(element, errorClass, validClass) {
  221. if (element.type === 'radio') {
  222. this.findByName(element.name).addClass(errorClass).removeClass(validClass);
  223. } else {
  224. $(element).addClass(errorClass).removeClass(validClass);
  225. }
  226. },
  227. unhighlight: function(element, errorClass, validClass) {
  228. if (element.type === 'radio') {
  229. this.findByName(element.name).removeClass(errorClass).addClass(validClass);
  230. } else {
  231. $(element).removeClass(errorClass).addClass(validClass);
  232. }
  233. }
  234. },
  235. // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
  236. setDefaults: function(settings) {
  237. $.extend( $.validator.defaults, settings );
  238. },
  239. messages: {
  240. required: "This field is required.",
  241. remote: "Please fix this field.",
  242. email: "Please enter a valid email address.",
  243. url: "Please enter a valid URL.",
  244. date: "Please enter a valid date.",
  245. dateISO: "Please enter a valid date (ISO).",
  246. number: "Please enter a valid number.",
  247. digits: "Please enter only digits.",
  248. creditcard: "Please enter a valid credit card number.",
  249. equalTo: "Please enter the same value again.",
  250. accept: "Please enter a value with a valid extension.",
  251. maxlength: $.validator.format("Please enter no more than {0} characters."),
  252. minlength: $.validator.format("Please enter at least {0} characters."),
  253. rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
  254. range: $.validator.format("Please enter a value between {0} and {1}."),
  255. max: $.validator.format("Please enter a value less than or equal to {0}."),
  256. min: $.validator.format("Please enter a value greater than or equal to {0}.")
  257. },
  258. autoCreateRanges: false,
  259. prototype: {
  260. init: function() {
  261. this.labelContainer = $(this.settings.errorLabelContainer);
  262. this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
  263. this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
  264. this.submitted = {};
  265. this.valueCache = {};
  266. this.pendingRequest = 0;
  267. this.pending = {};
  268. this.invalid = {};
  269. this.reset();
  270. var groups = (this.groups = {});
  271. $.each(this.settings.groups, function(key, value) {
  272. $.each(value.split(/\s/), function(index, name) {
  273. groups[name] = key;
  274. });
  275. });
  276. var rules = this.settings.rules;
  277. $.each(rules, function(key, value) {
  278. rules[key] = $.validator.normalizeRule(value);
  279. });
  280. function delegate(event) {
  281. var validator = $.data(this[0].form, "validator"),
  282. eventType = "on" + event.type.replace(/^validate/, "");
  283. validator.settings[eventType] && validator.settings[eventType].call(validator, this[0], event);
  284. }
  285. $(this.currentForm)
  286. .validateDelegate("[type='text'], [type='password'], [type='file'], select, textarea, " +
  287. "[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
  288. "[type='email'], [type='datetime'], [type='date'], [type='month'], " +
  289. "[type='week'], [type='time'], [type='datetime-local'], " +
  290. "[type='range'], [type='color'] ",
  291. "focusin focusout keyup", delegate)
  292. .validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate);
  293. if (this.settings.invalidHandler)
  294. $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
  295. },
  296. // http://docs.jquery.com/Plugins/Validation/Validator/form
  297. form: function() {
  298. this.checkForm();
  299. $.extend(this.submitted, this.errorMap);
  300. this.invalid = $.extend({}, this.errorMap);
  301. if (!this.valid())
  302. $(this.currentForm).triggerHandler("invalid-form", [this]);
  303. this.showErrors();
  304. return this.valid();
  305. },
  306. checkForm: function() {
  307. this.prepareForm();
  308. for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
  309. this.check( elements[i] );
  310. }
  311. return this.valid();
  312. },
  313. // http://docs.jquery.com/Plugins/Validation/Validator/element
  314. element: function( element ) {
  315. element = this.validationTargetFor( this.clean( element ) );
  316. this.lastElement = element;
  317. this.prepareElement( element );
  318. this.currentElements = $(element);
  319. var result = this.check( element );
  320. if ( result ) {
  321. delete this.invalid[element.name];
  322. } else {
  323. this.invalid[element.name] = true;
  324. }
  325. if ( !this.numberOfInvalids() ) {
  326. // Hide error containers on last error
  327. this.toHide = this.toHide.add( this.containers );
  328. }
  329. this.showErrors();
  330. return result;
  331. },
  332. // http://docs.jquery.com/Plugins/Validation/Validator/showErrors
  333. showErrors: function(errors) {
  334. if(errors) {
  335. // add items to error list and map
  336. $.extend( this.errorMap, errors );
  337. this.errorList = [];
  338. for ( var name in errors ) {
  339. this.errorList.push({
  340. message: errors[name],
  341. element: this.findByName(name)[0]
  342. });
  343. }
  344. // remove items from success list
  345. this.successList = $.grep( this.successList, function(element) {
  346. return !(element.name in errors);
  347. });
  348. }
  349. this.settings.showErrors
  350. ? this.settings.showErrors.call( this, this.errorMap, this.errorList )
  351. : this.defaultShowErrors();
  352. },
  353. // http://docs.jquery.com/Plugins/Validation/Validator/resetForm
  354. resetForm: function() {
  355. if ( $.fn.resetForm )
  356. $( this.currentForm ).resetForm();
  357. this.submitted = {};
  358. this.lastElement = null;
  359. this.prepareForm();
  360. this.hideErrors();
  361. this.elements().removeClass( this.settings.errorClass );
  362. },
  363. numberOfInvalids: function() {
  364. return this.objectLength(this.invalid);
  365. },
  366. objectLength: function( obj ) {
  367. var count = 0;
  368. for ( var i in obj )
  369. count++;
  370. return count;
  371. },
  372. hideErrors: function() {
  373. this.addWrapper( this.toHide ).hide();
  374. },
  375. valid: function() {
  376. return this.size() == 0;
  377. },
  378. size: function() {
  379. return this.errorList.length;
  380. },
  381. focusInvalid: function() {
  382. if( this.settings.focusInvalid ) {
  383. try {
  384. $(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
  385. .filter(":visible")
  386. .focus()
  387. // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
  388. .trigger("focusin");
  389. } catch(e) {
  390. // ignore IE throwing errors when focusing hidden elements
  391. }
  392. }
  393. },
  394. findLastActive: function() {
  395. var lastActive = this.lastActive;
  396. return lastActive && $.grep(this.errorList, function(n) {
  397. return n.element.name == lastActive.name;
  398. }).length == 1 && lastActive;
  399. },
  400. elements: function() {
  401. var validator = this,
  402. rulesCache = {};
  403. // select all valid inputs inside the form (no submit or reset buttons)
  404. return $(this.currentForm)
  405. .find("input, select, textarea")
  406. .not(":submit, :reset, :image, [disabled]")
  407. .not( this.settings.ignore )
  408. .filter(function() {
  409. !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);
  410. // select only the first element for each name, and only those with rules specified
  411. if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
  412. return false;
  413. rulesCache[this.name] = true;
  414. return true;
  415. });
  416. },
  417. clean: function( selector ) {
  418. return $( selector )[0];
  419. },
  420. errors: function() {
  421. return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
  422. },
  423. reset: function() {
  424. this.successList = [];
  425. this.errorList = [];
  426. this.errorMap = {};
  427. this.toShow = $([]);
  428. this.toHide = $([]);
  429. this.currentElements = $([]);
  430. },
  431. prepareForm: function() {
  432. this.reset();
  433. this.toHide = this.errors().add( this.containers );
  434. },
  435. prepareElement: function( element ) {
  436. this.reset();
  437. this.toHide = this.errorsFor(element);
  438. },
  439. check: function( element ) {
  440. element = this.validationTargetFor( this.clean( element ) );
  441. var rules = $(element).rules();
  442. var dependencyMismatch = false;
  443. for (var method in rules ) {
  444. var rule = { method: method, parameters: rules[method] };
  445. try {
  446. var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );
  447. // if a method indicates that the field is optional and therefore valid,
  448. // don't mark it as valid when there are no other rules
  449. if ( result == "dependency-mismatch" ) {
  450. dependencyMismatch = true;
  451. continue;
  452. }
  453. dependencyMismatch = false;
  454. if ( result == "pending" ) {
  455. this.toHide = this.toHide.not( this.errorsFor(element) );
  456. return;
  457. }
  458. if( !result ) {
  459. this.formatAndAdd( element, rule );
  460. return false;
  461. }
  462. } catch(e) {
  463. this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
  464. + ", check the '" + rule.method + "' method", e);
  465. throw e;
  466. }
  467. }
  468. if (dependencyMismatch)
  469. return;
  470. if ( this.objectLength(rules) )
  471. this.successList.push(element);
  472. return true;
  473. },
  474. // return the custom message for the given element and validation method
  475. // specified in the element's "messages" metadata
  476. customMetaMessage: function(element, method) {
  477. if (!$.metadata)
  478. return;
  479. var meta = this.settings.meta
  480. ? $(element).metadata()[this.settings.meta]
  481. : $(element).metadata();
  482. return meta && meta.messages && meta.messages[method];
  483. },
  484. // return the custom message for the given element name and validation method
  485. customMessage: function( name, method ) {
  486. var m = this.settings.messages[name];
  487. return m && (m.constructor == String
  488. ? m
  489. : m[method]);
  490. },
  491. // return the first defined argument, allowing empty strings
  492. findDefined: function() {
  493. for(var i = 0; i < arguments.length; i++) {
  494. if (arguments[i] !== undefined)
  495. return arguments[i];
  496. }
  497. return undefined;
  498. },
  499. defaultMessage: function( element, method) {
  500. return this.findDefined(
  501. this.customMessage( element.name, method ),
  502. this.customMetaMessage( element, method ),
  503. // title is never undefined, so handle empty string as undefined
  504. !this.settings.ignoreTitle && element.title || undefined,
  505. $.validator.messages[method],
  506. "<strong>Warning: No message defined for " + element.name + "</strong>"
  507. );
  508. },
  509. formatAndAdd: function( element, rule ) {
  510. var message = this.defaultMessage( element, rule.method ),
  511. theregex = /\$?\{(\d+)\}/g;
  512. if ( typeof message == "function" ) {
  513. message = message.call(this, rule.parameters, element);
  514. } else if (theregex.test(message)) {
  515. message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters);
  516. }
  517. this.errorList.push({
  518. message: message,
  519. element: element
  520. });
  521. this.errorMap[element.name] = message;
  522. this.submitted[element.name] = message;
  523. },
  524. addWrapper: function(toToggle) {
  525. if ( this.settings.wrapper )
  526. toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
  527. return toToggle;
  528. },
  529. defaultShowErrors: function() {
  530. for ( var i = 0; this.errorList[i]; i++ ) {
  531. var error = this.errorList[i];
  532. this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
  533. this.showLabel( error.element, error.message );
  534. }
  535. if( this.errorList.length ) {
  536. this.toShow = this.toShow.add( this.containers );
  537. }
  538. if (this.settings.success) {
  539. for ( var i = 0; this.successList[i]; i++ ) {
  540. this.showLabel( this.successList[i] );
  541. }
  542. }
  543. if (this.settings.unhighlight) {
  544. for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
  545. this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
  546. }
  547. }
  548. this.toHide = this.toHide.not( this.toShow );
  549. this.hideErrors();
  550. this.addWrapper( this.toShow ).show();
  551. },
  552. validElements: function() {
  553. return this.currentElements.not(this.invalidElements());
  554. },
  555. invalidElements: function() {
  556. return $(this.errorList).map(function() {
  557. return this.element;
  558. });
  559. },
  560. showLabel: function(element, message) {
  561. var label = this.errorsFor( element );
  562. if ( label.length ) {
  563. // refresh error/success class
  564. label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
  565. // check if we have a generated label, replace the message then
  566. label.attr("generated") && label.html(message);
  567. } else {
  568. // create label
  569. label = $("<" + this.settings.errorElement + "/>")
  570. .attr({"for": this.idOrName(element), generated: true})
  571. .addClass(this.settings.errorClass)
  572. .html(message || "");
  573. if ( this.settings.wrapper ) {
  574. // make sure the element is visible, even in IE
  575. // actually showing the wrapped element is handled elsewhere
  576. label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
  577. }
  578. if ( !this.labelContainer.append(label).length )
  579. this.settings.errorPlacement
  580. ? this.settings.errorPlacement(label, $(element) )
  581. : label.insertAfter(element);
  582. }
  583. if ( !message && this.settings.success ) {
  584. label.text("");
  585. typeof this.settings.success == "string"
  586. ? label.addClass( this.settings.success )
  587. : this.settings.success( label );
  588. }
  589. this.toShow = this.toShow.add(label);
  590. },
  591. errorsFor: function(element) {
  592. var name = this.idOrName(element);
  593. return this.errors().filter(function() {
  594. return $(this).attr('for') == name;
  595. });
  596. },
  597. idOrName: function(element) {
  598. return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
  599. },
  600. validationTargetFor: function(element) {
  601. // if radio/checkbox, validate first element in group instead
  602. if (this.checkable(element)) {
  603. element = this.findByName( element.name ).not(this.settings.ignore)[0];
  604. }
  605. return element;
  606. },
  607. checkable: function( element ) {
  608. return /radio|checkbox/i.test(element.type);
  609. },
  610. findByName: function( name ) {
  611. // select by name and filter by form for performance over form.find("[name=...]")
  612. var form = this.currentForm;
  613. return $(document.getElementsByName(name)).map(function(index, element) {
  614. return element.form == form && element.name == name && element || null;
  615. });
  616. },
  617. getLength: function(value, element) {
  618. switch( element.nodeName.toLowerCase() ) {
  619. case 'select':
  620. return $("option:selected", element).length;
  621. case 'input':
  622. if( this.checkable( element) )
  623. return this.findByName(element.name).filter(':checked').length;
  624. }
  625. return value.length;
  626. },
  627. depend: function(param, element) {
  628. return this.dependTypes[typeof param]
  629. ? this.dependTypes[typeof param](param, element)
  630. : true;
  631. },
  632. dependTypes: {
  633. "boolean": function(param, element) {
  634. return param;
  635. },
  636. "string": function(param, element) {
  637. return !!$(param, element.form).length;
  638. },
  639. "function": function(param, element) {
  640. return param(element);
  641. }
  642. },
  643. optional: function(element) {
  644. return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
  645. },
  646. startRequest: function(element) {
  647. if (!this.pending[element.name]) {
  648. this.pendingRequest++;
  649. this.pending[element.name] = true;
  650. }
  651. },
  652. stopRequest: function(element, valid) {
  653. this.pendingRequest--;
  654. // sometimes synchronization fails, make sure pendingRequest is never < 0
  655. if (this.pendingRequest < 0)
  656. this.pendingRequest = 0;
  657. delete this.pending[element.name];
  658. if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
  659. $(this.currentForm).submit();
  660. this.formSubmitted = false;
  661. } else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
  662. $(this.currentForm).triggerHandler("invalid-form", [this]);
  663. this.formSubmitted = false;
  664. }
  665. },
  666. previousValue: function(element) {
  667. return $.data(element, "previousValue") || $.data(element, "previousValue", {
  668. old: null,
  669. valid: true,
  670. message: this.defaultMessage( element, "remote" )
  671. });
  672. }
  673. },
  674. classRuleSettings: {
  675. required: {required: true},
  676. email: {email: true},
  677. url: {url: true},
  678. date: {date: true},
  679. dateISO: {dateISO: true},
  680. dateDE: {dateDE: true},
  681. number: {number: true},
  682. numberDE: {numberDE: true},
  683. digits: {digits: true},
  684. creditcard: {creditcard: true}
  685. },
  686. addClassRules: function(className, rules) {
  687. className.constructor == String ?
  688. this.classRuleSettings[className] = rules :
  689. $.extend(this.classRuleSettings, className);
  690. },
  691. classRules: function(element) {
  692. var rules = {};
  693. var classes = $(element).attr('class');
  694. classes && $.each(classes.split(' '), function() {
  695. if (this in $.validator.classRuleSettings) {
  696. $.extend(rules, $.validator.classRuleSettings[this]);
  697. }
  698. });
  699. return rules;
  700. },
  701. attributeRules: function(element) {
  702. var rules = {};
  703. var $element = $(element);
  704. for (var method in $.validator.methods) {
  705. var value;
  706. // If .prop exists (jQuery >= 1.6), use it to get true/false for required
  707. if (method === 'required' && typeof $.fn.prop === 'function') {
  708. value = $element.prop(method);
  709. } else {
  710. value = $element.attr(method);
  711. }
  712. if (value) {
  713. rules[method] = value;
  714. } else if ($element[0].getAttribute("type") === method) {
  715. rules[method] = true;
  716. }
  717. }
  718. // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
  719. if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
  720. delete rules.maxlength;
  721. }
  722. return rules;
  723. },
  724. metadataRules: function(element) {
  725. if (!$.metadata) return {};
  726. var meta = $.data(element.form, 'validator').settings.meta;
  727. return meta ?
  728. $(element).metadata()[meta] :
  729. $(element).metadata();
  730. },
  731. staticRules: function(element) {
  732. var rules = {};
  733. var validator = $.data(element.form, 'validator');
  734. if (validator.settings.rules) {
  735. rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
  736. }
  737. return rules;
  738. },
  739. normalizeRules: function(rules, element) {
  740. // handle dependency check
  741. $.each(rules, function(prop, val) {
  742. // ignore rule when param is explicitly false, eg. required:false
  743. if (val === false) {
  744. delete rules[prop];
  745. return;
  746. }
  747. if (val.param || val.depends) {
  748. var keepRule = true;
  749. switch (typeof val.depends) {
  750. case "string":
  751. keepRule = !!$(val.depends, element.form).length;
  752. break;
  753. case "function":
  754. keepRule = val.depends.call(element, element);
  755. break;
  756. }
  757. if (keepRule) {
  758. rules[prop] = val.param !== undefined ? val.param : true;
  759. } else {
  760. delete rules[prop];
  761. }
  762. }
  763. });
  764. // evaluate parameters
  765. $.each(rules, function(rule, parameter) {
  766. rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
  767. });
  768. // clean number parameters
  769. $.each(['minlength', 'maxlength', 'min', 'max'], function() {
  770. if (rules[this]) {
  771. rules[this] = Number(rules[this]);
  772. }
  773. });
  774. $.each(['rangelength', 'range'], function() {
  775. if (rules[this]) {
  776. rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
  777. }
  778. });
  779. if ($.validator.autoCreateRanges) {
  780. // auto-create ranges
  781. if (rules.min && rules.max) {
  782. rules.range = [rules.min, rules.max];
  783. delete rules.min;
  784. delete rules.max;
  785. }
  786. if (rules.minlength && rules.maxlength) {
  787. rules.rangelength = [rules.minlength, rules.maxlength];
  788. delete rules.minlength;
  789. delete rules.maxlength;
  790. }
  791. }
  792. // To support custom messages in metadata ignore rule methods titled "messages"
  793. if (rules.messages) {
  794. delete rules.messages;
  795. }
  796. return rules;
  797. },
  798. // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
  799. normalizeRule: function(data) {
  800. if( typeof data == "string" ) {
  801. var transformed = {};
  802. $.each(data.split(/\s/), function() {
  803. transformed[this] = true;
  804. });
  805. data = transformed;
  806. }
  807. return data;
  808. },
  809. // http://docs.jquery.com/Plugins/Validation/Validator/addMethod
  810. addMethod: function(name, method, message) {
  811. $.validator.methods[name] = method;
  812. $.validator.messages[name] = message != undefined ? message : $.validator.messages[name];
  813. if (method.length < 3) {
  814. $.validator.addClassRules(name, $.validator.normalizeRule(name));
  815. }
  816. },
  817. methods: {
  818. // http://docs.jquery.com/Plugins/Validation/Methods/required
  819. required: function(value, element, param) {
  820. // check if dependency is met
  821. if ( !this.depend(param, element) )
  822. return "dependency-mismatch";
  823. switch( element.nodeName.toLowerCase() ) {
  824. case 'select':
  825. // could be an array for select-multiple or a string, both are fine this way
  826. var val = $(element).val();
  827. return val && val.length > 0;
  828. case 'input':
  829. if ( this.checkable(element) )
  830. return this.getLength(value, element) > 0;
  831. default:
  832. return $.trim(value).length > 0;
  833. }
  834. },
  835. // http://docs.jquery.com/Plugins/Validation/Methods/remote
  836. remote: function(value, element, param) {
  837. if ( this.optional(element) )
  838. return "dependency-mismatch";
  839. var previous = this.previousValue(element);
  840. if (!this.settings.messages[element.name] )
  841. this.settings.messages[element.name] = {};
  842. previous.originalMessage = this.settings.messages[element.name].remote;
  843. this.settings.messages[element.name].remote = previous.message;
  844. param = typeof param == "string" && {url:param} || param;
  845. if ( this.pending[element.name] ) {
  846. return "pending";
  847. }
  848. if ( previous.old === value ) {
  849. return previous.valid;
  850. }
  851. previous.old = value;
  852. var validator = this;
  853. this.startRequest(element);
  854. var data = {};
  855. data[element.name] = value;
  856. $.ajax($.extend(true, {
  857. url: param,
  858. mode: "abort",
  859. port: "validate" + element.name,
  860. dataType: "json",
  861. data: data,
  862. success: function(response) {
  863. validator.settings.messages[element.name].remote = previous.originalMessage;
  864. var valid = response === true;
  865. if ( valid ) {
  866. var submitted = validator.formSubmitted;
  867. validator.prepareElement(element);
  868. validator.formSubmitted = submitted;
  869. validator.successList.push(element);
  870. validator.showErrors();
  871. } else {
  872. var errors = {};
  873. var message = response || validator.defaultMessage( element, "remote" );
  874. errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
  875. validator.showErrors(errors);
  876. }
  877. previous.valid = valid;
  878. validator.stopRequest(element, valid);
  879. }
  880. }, param));
  881. return "pending";
  882. },
  883. // http://docs.jquery.com/Plugins/Validation/Methods/minlength
  884. minlength: function(value, element, param) {
  885. return this.optional(element) || this.getLength($.trim(value), element) >= param;
  886. },
  887. // http://docs.jquery.com/Plugins/Validation/Methods/maxlength
  888. maxlength: function(value, element, param) {
  889. return this.optional(element) || this.getLength($.trim(value), element) <= param;
  890. },
  891. // http://docs.jquery.com/Plugins/Validation/Methods/rangelength
  892. rangelength: function(value, element, param) {
  893. var length = this.getLength($.trim(value), element);
  894. return this.optional(element) || ( length >= param[0] && length <= param[1] );
  895. },
  896. // http://docs.jquery.com/Plugins/Validation/Methods/min
  897. min: function( value, element, param ) {
  898. return this.optional(element) || value >= param;
  899. },
  900. // http://docs.jquery.com/Plugins/Validation/Methods/max
  901. max: function( value, element, param ) {
  902. return this.optional(element) || value <= param;
  903. },
  904. // http://docs.jquery.com/Plugins/Validation/Methods/range
  905. range: function( value, element, param ) {
  906. return this.optional(element) || ( value >= param[0] && value <= param[1] );
  907. },
  908. // http://docs.jquery.com/Plugins/Validation/Methods/email
  909. email: function(value, element) {
  910. // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
  911. return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([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])))$/i.test(value);
  912. },
  913. // http://docs.jquery.com/Plugins/Validation/Methods/url
  914. url: function(value, element) {
  915. // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
  916. return this.optional(element) || /^(https?|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);
  917. },
  918. // http://docs.jquery.com/Plugins/Validation/Methods/date
  919. date: function(value, element) {
  920. return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
  921. },
  922. // http://docs.jquery.com/Plugins/Validation/Methods/dateISO
  923. dateISO: function(value, element) {
  924. return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
  925. },
  926. // http://docs.jquery.com/Plugins/Validation/Methods/number
  927. number: function(value, element) {
  928. return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
  929. },
  930. // http://docs.jquery.com/Plugins/Validation/Methods/digits
  931. digits: function(value, element) {
  932. return this.optional(element) || /^\d+$/.test(value);
  933. },
  934. // http://docs.jquery.com/Plugins/Validation/Methods/creditcard
  935. // based on http://en.wikipedia.org/wiki/Luhn
  936. creditcard: function(value, element) {
  937. if ( this.optional(element) )
  938. return "dependency-mismatch";
  939. // accept only spaces, digits and dashes
  940. if (/[^0-9 -]+/.test(value))
  941. return false;
  942. var nCheck = 0,
  943. nDigit = 0,
  944. bEven = false;
  945. value = value.replace(/\D/g, "");
  946. for (var n = value.length - 1; n >= 0; n--) {
  947. var cDigit = value.charAt(n);
  948. var nDigit = parseInt(cDigit, 10);
  949. if (bEven) {
  950. if ((nDigit *= 2) > 9)
  951. nDigit -= 9;
  952. }
  953. nCheck += nDigit;
  954. bEven = !bEven;
  955. }
  956. return (nCheck % 10) == 0;
  957. },
  958. // http://docs.jquery.com/Plugins/Validation/Methods/accept
  959. accept: function(value, element, param) {
  960. param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
  961. return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
  962. },
  963. // http://docs.jquery.com/Plugins/Validation/Methods/equalTo
  964. equalTo: function(value, element, param) {
  965. // bind to the blur event of the target in order to revalidate whenever the target field is updated
  966. // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
  967. var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
  968. $(element).valid();
  969. });
  970. return value == target.val();
  971. }
  972. }
  973. });
  974. // deprecated, use $.validator.format instead
  975. $.format = $.validator.format;
  976. })(jQuery);
  977. // ajax mode: abort
  978. // usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
  979. // if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
  980. ;(function($) {
  981. var pendingRequests = {};
  982. // Use a prefilter if available (1.5+)
  983. if ( $.ajaxPrefilter ) {
  984. $.ajaxPrefilter(function(settings, _, xhr) {
  985. var port = settings.port;
  986. if (settings.mode == "abort") {
  987. if ( pendingRequests[port] ) {
  988. pendingRequests[port].abort();
  989. }
  990. pendingRequests[port] = xhr;
  991. }
  992. });
  993. } else {
  994. // Proxy ajax
  995. var ajax = $.ajax;
  996. $.ajax = function(settings) {
  997. var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
  998. port = ( "port" in settings ? settings : $.ajaxSettings ).port;
  999. if (mode == "abort") {
  1000. if ( pendingRequests[port] ) {
  1001. pendingRequests[port].abort();
  1002. }
  1003. return (pendingRequests[port] = ajax.apply(this, arguments));
  1004. }
  1005. return ajax.apply(this, arguments);
  1006. };
  1007. }
  1008. })(jQuery);
  1009. // provides cross-browser focusin and focusout events
  1010. // IE has native support, in other browsers, use event caputuring (neither bubbles)
  1011. // provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
  1012. // handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
  1013. ;(function($) {
  1014. // only implement if not provided by jQuery core (since 1.4)
  1015. // TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs
  1016. if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) {
  1017. $.each({
  1018. focus: 'focusin',
  1019. blur: 'focusout'
  1020. }, function( original, fix ){
  1021. $.event.special[fix] = {
  1022. setup:function() {
  1023. this.addEventListener( original, handler, true );
  1024. },
  1025. teardown:function() {
  1026. this.removeEventListener( original, handler, true );
  1027. },
  1028. handler: function(e) {
  1029. arguments[0] = $.event.fix(e);
  1030. arguments[0].type = fix;
  1031. return $.event.handle.apply(this, arguments);
  1032. }
  1033. };
  1034. function handler(e) {
  1035. e = $.event.fix(e);
  1036. e.type = fix;
  1037. return $.event.handle.call(this, e);
  1038. }
  1039. });
  1040. };
  1041. $.extend($.fn, {
  1042. validateDelegate: function(delegate, type, handler) {
  1043. return this.bind(type, function(event) {
  1044. var target = $(event.target);
  1045. if (target.is(delegate)) {
  1046. return handler.apply(target, arguments);
  1047. }
  1048. });
  1049. }
  1050. });
  1051. })(jQuery);