PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/jquery-validate/jquery.validate.js

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