Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

429 righe
19 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. key = '__jquery_unobtrusive_validation_form_reset';
  87. if ($form.data(key)) {
  88. return;
  89. }
  90. // Set a flag that indicates we're currently resetting the form.
  91. $form.data(key, true);
  92. try {
  93. $form.data("validator").resetForm();
  94. } finally {
  95. $form.removeData(key);
  96. }
  97. $form.find(".validation-summary-errors")
  98. .addClass("validation-summary-valid")
  99. .removeClass("validation-summary-errors");
  100. $form.find(".field-validation-error")
  101. .addClass("field-validation-valid")
  102. .removeClass("field-validation-error")
  103. .removeData("unobtrusiveContainer")
  104. .find(">*") // If we were using valmsg-replace, get the underlying error
  105. .removeData("unobtrusiveContainer");
  106. }
  107. function validationInfo(form) {
  108. var $form = $(form),
  109. result = $form.data(data_validation),
  110. onResetProxy = $.proxy(onReset, form),
  111. defaultOptions = $jQval.unobtrusive.options || {},
  112. execInContext = function (name, args) {
  113. var func = defaultOptions[name];
  114. func && $.isFunction(func) && func.apply(form, args);
  115. }
  116. if (!result) {
  117. result = {
  118. options: { // options structure passed to jQuery Validate's validate() method
  119. errorClass: defaultOptions.errorClass || "input-validation-error",
  120. errorElement: defaultOptions.errorElement || "span",
  121. errorPlacement: function () {
  122. onError.apply(form, arguments);
  123. execInContext("errorPlacement", arguments);
  124. },
  125. invalidHandler: function () {
  126. onErrors.apply(form, arguments);
  127. execInContext("invalidHandler", arguments);
  128. },
  129. messages: {},
  130. rules: {},
  131. success: function () {
  132. onSuccess.apply(form, arguments);
  133. execInContext("success", arguments);
  134. }
  135. },
  136. attachValidation: function () {
  137. $form
  138. .off("reset." + data_validation, onResetProxy)
  139. .on("reset." + data_validation, onResetProxy)
  140. .validate(this.options);
  141. },
  142. validate: function () { // a validation function that is called by unobtrusive Ajax
  143. $form.validate();
  144. return $form.valid();
  145. }
  146. };
  147. $form.data(data_validation, result);
  148. }
  149. return result;
  150. }
  151. $jQval.unobtrusive = {
  152. adapters: [],
  153. parseElement: function (element, skipAttach) {
  154. /// <summary>
  155. /// Parses a single HTML element for unobtrusive validation attributes.
  156. /// </summary>
  157. /// <param name="element" domElement="true">The HTML element to be parsed.</param>
  158. /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
  159. /// validation to the form. If parsing just this single element, you should specify true.
  160. /// If parsing several elements, you should specify false, and manually attach the validation
  161. /// to the form when you are finished. The default is false.</param>
  162. var $element = $(element),
  163. form = $element.parents("form")[0],
  164. valInfo, rules, messages;
  165. if (!form) { // Cannot do client-side validation without a form
  166. return;
  167. }
  168. valInfo = validationInfo(form);
  169. valInfo.options.rules[element.name] = rules = {};
  170. valInfo.options.messages[element.name] = messages = {};
  171. $.each(this.adapters, function () {
  172. var prefix = "data-val-" + this.name,
  173. message = $element.attr(prefix),
  174. paramValues = {};
  175. if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
  176. prefix += "-";
  177. $.each(this.params, function () {
  178. paramValues[this] = $element.attr(prefix + this);
  179. });
  180. this.adapt({
  181. element: element,
  182. form: form,
  183. message: message,
  184. params: paramValues,
  185. rules: rules,
  186. messages: messages
  187. });
  188. }
  189. });
  190. $.extend(rules, { "__dummy__": true });
  191. if (!skipAttach) {
  192. valInfo.attachValidation();
  193. }
  194. },
  195. parse: function (selector) {
  196. /// <summary>
  197. /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
  198. /// with the [data-val=true] attribute value and enables validation according to the data-val-*
  199. /// attribute values.
  200. /// </summary>
  201. /// <param name="selector" type="String">Any valid jQuery selector.</param>
  202. // $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
  203. // element with data-val=true
  204. var $selector = $(selector),
  205. $forms = $selector.parents()
  206. .addBack()
  207. .filter("form")
  208. .add($selector.find("form"))
  209. .has("[data-val=true]");
  210. $selector.find("[data-val=true]").each(function () {
  211. $jQval.unobtrusive.parseElement(this, true);
  212. });
  213. $forms.each(function () {
  214. var info = validationInfo(this);
  215. if (info) {
  216. info.attachValidation();
  217. }
  218. });
  219. }
  220. };
  221. adapters = $jQval.unobtrusive.adapters;
  222. adapters.add = function (adapterName, params, fn) {
  223. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
  224. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  225. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  226. /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
  227. /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
  228. /// mmmm is the parameter name).</param>
  229. /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
  230. /// attributes into jQuery Validate rules and/or messages.</param>
  231. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  232. if (!fn) { // Called with no params, just a function
  233. fn = params;
  234. params = [];
  235. }
  236. this.push({ name: adapterName, params: params, adapt: fn });
  237. return this;
  238. };
  239. adapters.addBool = function (adapterName, ruleName) {
  240. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  241. /// the jQuery Validate validation rule has no parameter values.</summary>
  242. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  243. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  244. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  245. /// of adapterName will be used instead.</param>
  246. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  247. return this.add(adapterName, function (options) {
  248. setValidationValues(options, ruleName || adapterName, true);
  249. });
  250. };
  251. adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
  252. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  253. /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
  254. /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
  255. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  256. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  257. /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  258. /// have a minimum value.</param>
  259. /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  260. /// have a maximum value.</param>
  261. /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
  262. /// have both a minimum and maximum value.</param>
  263. /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  264. /// contains the minimum value. The default is "min".</param>
  265. /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  266. /// contains the maximum value. The default is "max".</param>
  267. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  268. return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
  269. var min = options.params.min,
  270. max = options.params.max;
  271. if (min && max) {
  272. setValidationValues(options, minMaxRuleName, [min, max]);
  273. }
  274. else if (min) {
  275. setValidationValues(options, minRuleName, min);
  276. }
  277. else if (max) {
  278. setValidationValues(options, maxRuleName, max);
  279. }
  280. });
  281. };
  282. adapters.addSingleVal = function (adapterName, attribute, ruleName) {
  283. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  284. /// the jQuery Validate validation rule has a single value.</summary>
  285. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  286. /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
  287. /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
  288. /// The default is "val".</param>
  289. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  290. /// of adapterName will be used instead.</param>
  291. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  292. return this.add(adapterName, [attribute || "val"], function (options) {
  293. setValidationValues(options, ruleName || adapterName, options.params[attribute]);
  294. });
  295. };
  296. $jQval.addMethod("__dummy__", function (value, element, params) {
  297. return true;
  298. });
  299. $jQval.addMethod("regex", function (value, element, params) {
  300. var match;
  301. if (this.optional(element)) {
  302. return true;
  303. }
  304. match = new RegExp(params).exec(value);
  305. return (match && (match.index === 0) && (match[0].length === value.length));
  306. });
  307. $jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
  308. var match;
  309. if (nonalphamin) {
  310. match = value.match(/\W/g);
  311. match = match && match.length >= nonalphamin;
  312. }
  313. return match;
  314. });
  315. if ($jQval.methods.extension) {
  316. adapters.addSingleVal("accept", "mimtype");
  317. adapters.addSingleVal("extension", "extension");
  318. } else {
  319. // for backward compatibility, when the 'extension' validation method does not exist, such as with versions
  320. // of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
  321. // validating the extension, and ignore mime-type validations as they are not supported.
  322. adapters.addSingleVal("extension", "extension", "accept");
  323. }
  324. adapters.addSingleVal("regex", "pattern");
  325. adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
  326. adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
  327. adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
  328. adapters.add("equalto", ["other"], function (options) {
  329. var prefix = getModelPrefix(options.element.name),
  330. other = options.params.other,
  331. fullOtherName = appendModelPrefix(other, prefix),
  332. element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
  333. setValidationValues(options, "equalTo", element);
  334. });
  335. adapters.add("required", function (options) {
  336. // jQuery Validate equates "required" with "mandatory" for checkbox elements
  337. if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
  338. setValidationValues(options, "required", true);
  339. }
  340. });
  341. adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
  342. var value = {
  343. url: options.params.url,
  344. type: options.params.type || "GET",
  345. data: {}
  346. },
  347. prefix = getModelPrefix(options.element.name);
  348. $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
  349. var paramName = appendModelPrefix(fieldName, prefix);
  350. value.data[paramName] = function () {
  351. var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
  352. // For checkboxes and radio buttons, only pick up values from checked fields.
  353. if (field.is(":checkbox")) {
  354. return field.filter(":checked").val() || field.filter(":hidden").val() || '';
  355. }
  356. else if (field.is(":radio")) {
  357. return field.filter(":checked").val() || '';
  358. }
  359. return field.val();
  360. };
  361. });
  362. setValidationValues(options, "remote", value);
  363. });
  364. adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
  365. if (options.params.min) {
  366. setValidationValues(options, "minlength", options.params.min);
  367. }
  368. if (options.params.nonalphamin) {
  369. setValidationValues(options, "nonalphamin", options.params.nonalphamin);
  370. }
  371. if (options.params.regex) {
  372. setValidationValues(options, "regex", options.params.regex);
  373. }
  374. });
  375. $(function () {
  376. $jQval.unobtrusive.parse(document);
  377. });
  378. }(jQuery));