You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1289 lines
42 KiB

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