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.

393 lines
18 KiB

  1. /* NUGET: BEGIN LICENSE TEXT
  2. *
  3. * Microsoft grants you the right to use these script files for the sole
  4. * purpose of either: (i) interacting through your browser with the Microsoft
  5. * website or online service, subject to the applicable licensing or use
  6. * terms; or (ii) using the files as included with a Microsoft product subject
  7. * to that product's license terms. Microsoft reserves all other rights to the
  8. * files not expressly granted by Microsoft, whether by implication, estoppel
  9. * or otherwise. Insofar as a script file is dual licensed under GPL,
  10. * Microsoft neither took the code under GPL nor distributes it thereunder but
  11. * under the terms set out in this paragraph. All notices and licenses
  12. * below are for informational purposes only.
  13. *
  14. * NUGET: END LICENSE TEXT */
  15. /*!
  16. ** Unobtrusive validation support library for jQuery and jQuery Validate
  17. ** Copyright (C) Microsoft Corporation. All rights reserved.
  18. */
  19. /*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
  20. /*global document: false, jQuery: false */
  21. (function ($) {
  22. var $jQval = $.validator,
  23. adapters,
  24. data_validation = "unobtrusiveValidation";
  25. function setValidationValues(options, ruleName, value) {
  26. options.rules[ruleName] = value;
  27. if (options.message) {
  28. options.messages[ruleName] = options.message;
  29. }
  30. }
  31. function splitAndTrim(value) {
  32. return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
  33. }
  34. function escapeAttributeValue(value) {
  35. // As mentioned on http://api.jquery.com/category/selectors/
  36. return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
  37. }
  38. function getModelPrefix(fieldName) {
  39. return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
  40. }
  41. function appendModelPrefix(value, prefix) {
  42. if (value.indexOf("*.") === 0) {
  43. value = value.replace("*.", prefix);
  44. }
  45. return value;
  46. }
  47. function onError(error, inputElement) { // 'this' is the form element
  48. var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
  49. replaceAttrValue = container.attr("data-valmsg-replace"),
  50. replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
  51. container.removeClass("field-validation-valid").addClass("field-validation-error");
  52. error.data("unobtrusiveContainer", container);
  53. if (replace) {
  54. container.empty();
  55. error.removeClass("input-validation-error").appendTo(container);
  56. }
  57. else {
  58. error.hide();
  59. }
  60. }
  61. function onErrors(event, validator) { // 'this' is the form element
  62. var container = $(this).find("[data-valmsg-summary=true]"),
  63. list = container.find("ul");
  64. if (list && list.length && validator.errorList.length) {
  65. list.empty();
  66. container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
  67. $.each(validator.errorList, function () {
  68. $("<li />").html(this.message).appendTo(list);
  69. });
  70. }
  71. }
  72. function onSuccess(error) { // 'this' is the form element
  73. var container = error.data("unobtrusiveContainer"),
  74. replaceAttrValue = container.attr("data-valmsg-replace"),
  75. replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
  76. if (container) {
  77. container.addClass("field-validation-valid").removeClass("field-validation-error");
  78. error.removeData("unobtrusiveContainer");
  79. if (replace) {
  80. container.empty();
  81. }
  82. }
  83. }
  84. function onReset(event) { // 'this' is the form element
  85. var $form = $(this);
  86. $form.data("validator").resetForm();
  87. $form.find(".validation-summary-errors")
  88. .addClass("validation-summary-valid")
  89. .removeClass("validation-summary-errors");
  90. $form.find(".field-validation-error")
  91. .addClass("field-validation-valid")
  92. .removeClass("field-validation-error")
  93. .removeData("unobtrusiveContainer")
  94. .find(">*") // If we were using valmsg-replace, get the underlying error
  95. .removeData("unobtrusiveContainer");
  96. }
  97. function validationInfo(form) {
  98. var $form = $(form),
  99. result = $form.data(data_validation),
  100. onResetProxy = $.proxy(onReset, form);
  101. if (!result) {
  102. result = {
  103. options: { // options structure passed to jQuery Validate's validate() method
  104. errorClass: "input-validation-error",
  105. errorElement: "span",
  106. errorPlacement: $.proxy(onError, form),
  107. invalidHandler: $.proxy(onErrors, form),
  108. messages: {},
  109. rules: {},
  110. success: $.proxy(onSuccess, form)
  111. },
  112. attachValidation: function () {
  113. $form
  114. .unbind("reset." + data_validation, onResetProxy)
  115. .bind("reset." + data_validation, onResetProxy)
  116. .validate(this.options);
  117. },
  118. validate: function () { // a validation function that is called by unobtrusive Ajax
  119. $form.validate();
  120. return $form.valid();
  121. }
  122. };
  123. $form.data(data_validation, result);
  124. }
  125. return result;
  126. }
  127. $jQval.unobtrusive = {
  128. adapters: [],
  129. parseElement: function (element, skipAttach) {
  130. /// <summary>
  131. /// Parses a single HTML element for unobtrusive validation attributes.
  132. /// </summary>
  133. /// <param name="element" domElement="true">The HTML element to be parsed.</param>
  134. /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
  135. /// validation to the form. If parsing just this single element, you should specify true.
  136. /// If parsing several elements, you should specify false, and manually attach the validation
  137. /// to the form when you are finished. The default is false.</param>
  138. var $element = $(element),
  139. form = $element.parents("form")[0],
  140. valInfo, rules, messages;
  141. if (!form) { // Cannot do client-side validation without a form
  142. return;
  143. }
  144. valInfo = validationInfo(form);
  145. valInfo.options.rules[element.name] = rules = {};
  146. valInfo.options.messages[element.name] = messages = {};
  147. $.each(this.adapters, function () {
  148. var prefix = "data-val-" + this.name,
  149. message = $element.attr(prefix),
  150. paramValues = {};
  151. if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
  152. prefix += "-";
  153. $.each(this.params, function () {
  154. paramValues[this] = $element.attr(prefix + this);
  155. });
  156. this.adapt({
  157. element: element,
  158. form: form,
  159. message: message,
  160. params: paramValues,
  161. rules: rules,
  162. messages: messages
  163. });
  164. }
  165. });
  166. $.extend(rules, { "__dummy__": true });
  167. if (!skipAttach) {
  168. valInfo.attachValidation();
  169. }
  170. },
  171. parse: function (selector) {
  172. /// <summary>
  173. /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
  174. /// with the [data-val=true] attribute value and enables validation according to the data-val-*
  175. /// attribute values.
  176. /// </summary>
  177. /// <param name="selector" type="String">Any valid jQuery selector.</param>
  178. var $forms = $(selector)
  179. .parents("form")
  180. .andSelf()
  181. .add($(selector).find("form"))
  182. .filter("form");
  183. // :input is a psuedoselector provided by jQuery which selects input and input-like elements
  184. // combining :input with other selectors significantly decreases performance.
  185. $(selector).find(":input").filter("[data-val=true]").each(function () {
  186. $jQval.unobtrusive.parseElement(this, true);
  187. });
  188. $forms.each(function () {
  189. var info = validationInfo(this);
  190. if (info) {
  191. info.attachValidation();
  192. }
  193. });
  194. }
  195. };
  196. adapters = $jQval.unobtrusive.adapters;
  197. adapters.add = function (adapterName, params, fn) {
  198. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
  199. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  200. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  201. /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
  202. /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
  203. /// mmmm is the parameter name).</param>
  204. /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
  205. /// attributes into jQuery Validate rules and/or messages.</param>
  206. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  207. if (!fn) { // Called with no params, just a function
  208. fn = params;
  209. params = [];
  210. }
  211. this.push({ name: adapterName, params: params, adapt: fn });
  212. return this;
  213. };
  214. adapters.addBool = function (adapterName, ruleName) {
  215. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  216. /// the jQuery Validate validation rule has no parameter values.</summary>
  217. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  218. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  219. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  220. /// of adapterName will be used instead.</param>
  221. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  222. return this.add(adapterName, function (options) {
  223. setValidationValues(options, ruleName || adapterName, true);
  224. });
  225. };
  226. adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
  227. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  228. /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
  229. /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
  230. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  231. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  232. /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  233. /// have a minimum value.</param>
  234. /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  235. /// have a maximum value.</param>
  236. /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
  237. /// have both a minimum and maximum value.</param>
  238. /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  239. /// contains the minimum value. The default is "min".</param>
  240. /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  241. /// contains the maximum value. The default is "max".</param>
  242. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  243. return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
  244. var min = options.params.min,
  245. max = options.params.max;
  246. if (min && max) {
  247. setValidationValues(options, minMaxRuleName, [min, max]);
  248. }
  249. else if (min) {
  250. setValidationValues(options, minRuleName, min);
  251. }
  252. else if (max) {
  253. setValidationValues(options, maxRuleName, max);
  254. }
  255. });
  256. };
  257. adapters.addSingleVal = function (adapterName, attribute, ruleName) {
  258. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  259. /// the jQuery Validate validation rule has a single value.</summary>
  260. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  261. /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
  262. /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
  263. /// The default is "val".</param>
  264. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  265. /// of adapterName will be used instead.</param>
  266. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  267. return this.add(adapterName, [attribute || "val"], function (options) {
  268. setValidationValues(options, ruleName || adapterName, options.params[attribute]);
  269. });
  270. };
  271. $jQval.addMethod("__dummy__", function (value, element, params) {
  272. return true;
  273. });
  274. $jQval.addMethod("regex", function (value, element, params) {
  275. var match;
  276. if (this.optional(element)) {
  277. return true;
  278. }
  279. match = new RegExp(params).exec(value);
  280. return (match && (match.index === 0) && (match[0].length === value.length));
  281. });
  282. $jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
  283. var match;
  284. if (nonalphamin) {
  285. match = value.match(/\W/g);
  286. match = match && match.length >= nonalphamin;
  287. }
  288. return match;
  289. });
  290. if ($jQval.methods.extension) {
  291. adapters.addSingleVal("accept", "mimtype");
  292. adapters.addSingleVal("extension", "extension");
  293. } else {
  294. // for backward compatibility, when the 'extension' validation method does not exist, such as with versions
  295. // of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
  296. // validating the extension, and ignore mime-type validations as they are not supported.
  297. adapters.addSingleVal("extension", "extension", "accept");
  298. }
  299. adapters.addSingleVal("regex", "pattern");
  300. adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
  301. adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
  302. adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
  303. adapters.add("equalto", ["other"], function (options) {
  304. var prefix = getModelPrefix(options.element.name),
  305. other = options.params.other,
  306. fullOtherName = appendModelPrefix(other, prefix),
  307. element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
  308. setValidationValues(options, "equalTo", element);
  309. });
  310. adapters.add("required", function (options) {
  311. // jQuery Validate equates "required" with "mandatory" for checkbox elements
  312. if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
  313. setValidationValues(options, "required", true);
  314. }
  315. });
  316. adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
  317. var value = {
  318. url: options.params.url,
  319. type: options.params.type || "GET",
  320. data: {}
  321. },
  322. prefix = getModelPrefix(options.element.name);
  323. $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
  324. var paramName = appendModelPrefix(fieldName, prefix);
  325. value.data[paramName] = function () {
  326. return $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']").val();
  327. };
  328. });
  329. setValidationValues(options, "remote", value);
  330. });
  331. adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
  332. if (options.params.min) {
  333. setValidationValues(options, "minlength", options.params.min);
  334. }
  335. if (options.params.nonalphamin) {
  336. setValidationValues(options, "nonalphamin", options.params.nonalphamin);
  337. }
  338. if (options.params.regex) {
  339. setValidationValues(options, "regex", options.params.regex);
  340. }
  341. });
  342. $(function () {
  343. $jQval.unobtrusive.parse(document);
  344. });
  345. }(jQuery));