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.

1360 lines
57 KiB

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