PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/MvcMusicStore/Scripts/jquery.validate.unobtrusive.js

#
JavaScript | 319 lines | 210 code | 45 blank | 64 comment | 33 complexity | ee139f97ca2b67a45e43f377ccd02a3c MD5 | raw file
  1. /// <reference path="jquery-1.5.1.js" />
  2. /// <reference path="jquery.validate.js" />
  3. /*!
  4. ** Unobtrusive validation support library for jQuery and jQuery Validate
  5. ** Copyright (C) Microsoft Corporation. All rights reserved.
  6. */
  7. /*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 */
  8. /*global document: false, jQuery: false */
  9. (function ($) {
  10. var $jQval = $.validator,
  11. adapters,
  12. data_validation = "unobtrusiveValidation";
  13. function setValidationValues(options, ruleName, value) {
  14. options.rules[ruleName] = value;
  15. if (options.message) {
  16. options.messages[ruleName] = options.message;
  17. }
  18. }
  19. function splitAndTrim(value) {
  20. return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
  21. }
  22. function getModelPrefix(fieldName) {
  23. return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
  24. }
  25. function appendModelPrefix(value, prefix) {
  26. if (value.indexOf("*.") === 0) {
  27. value = value.replace("*.", prefix);
  28. }
  29. return value;
  30. }
  31. function onError(error, inputElement) { // 'this' is the form element
  32. var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
  33. replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
  34. container.removeClass("field-validation-valid").addClass("field-validation-error");
  35. error.data("unobtrusiveContainer", container);
  36. if (replace) {
  37. container.empty();
  38. error.removeClass("input-validation-error").appendTo(container);
  39. }
  40. else {
  41. error.hide();
  42. }
  43. }
  44. function onErrors(form, validator) { // 'this' is the form element
  45. var container = $(this).find("[data-valmsg-summary=true]"),
  46. list = container.find("ul");
  47. if (list && list.length && validator.errorList.length) {
  48. list.empty();
  49. container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
  50. $.each(validator.errorList, function () {
  51. $("<li />").html(this.message).appendTo(list);
  52. });
  53. }
  54. }
  55. function onSuccess(error) { // 'this' is the form element
  56. var container = error.data("unobtrusiveContainer"),
  57. replace = $.parseJSON(container.attr("data-valmsg-replace"));
  58. if (container) {
  59. container.addClass("field-validation-valid").removeClass("field-validation-error");
  60. error.removeData("unobtrusiveContainer");
  61. if (replace) {
  62. container.empty();
  63. }
  64. }
  65. }
  66. function validationInfo(form) {
  67. var $form = $(form),
  68. result = $form.data(data_validation);
  69. if (!result) {
  70. result = {
  71. options: { // options structure passed to jQuery Validate's validate() method
  72. errorClass: "input-validation-error",
  73. errorElement: "span",
  74. errorPlacement: $.proxy(onError, form),
  75. invalidHandler: $.proxy(onErrors, form),
  76. messages: {},
  77. rules: {},
  78. success: $.proxy(onSuccess, form)
  79. },
  80. attachValidation: function () {
  81. $form.validate(this.options);
  82. },
  83. validate: function () { // a validation function that is called by unobtrusive Ajax
  84. $form.validate();
  85. return $form.valid();
  86. }
  87. };
  88. $form.data(data_validation, result);
  89. }
  90. return result;
  91. }
  92. $jQval.unobtrusive = {
  93. adapters: [],
  94. parseElement: function (element, skipAttach) {
  95. /// <summary>
  96. /// Parses a single HTML element for unobtrusive validation attributes.
  97. /// </summary>
  98. /// <param name="element" domElement="true">The HTML element to be parsed.</param>
  99. /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
  100. /// validation to the form. If parsing just this single element, you should specify true.
  101. /// If parsing several elements, you should specify false, and manually attach the validation
  102. /// to the form when you are finished. The default is false.</param>
  103. var $element = $(element),
  104. form = $element.parents("form")[0],
  105. valInfo, rules, messages;
  106. if (!form) { // Cannot do client-side validation without a form
  107. return;
  108. }
  109. valInfo = validationInfo(form);
  110. valInfo.options.rules[element.name] = rules = {};
  111. valInfo.options.messages[element.name] = messages = {};
  112. $.each(this.adapters, function () {
  113. var prefix = "data-val-" + this.name,
  114. message = $element.attr(prefix),
  115. paramValues = {};
  116. if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
  117. prefix += "-";
  118. $.each(this.params, function () {
  119. paramValues[this] = $element.attr(prefix + this);
  120. });
  121. this.adapt({
  122. element: element,
  123. form: form,
  124. message: message,
  125. params: paramValues,
  126. rules: rules,
  127. messages: messages
  128. });
  129. }
  130. });
  131. jQuery.extend(rules, { "__dummy__": true });
  132. if (!skipAttach) {
  133. valInfo.attachValidation();
  134. }
  135. },
  136. parse: function (selector) {
  137. /// <summary>
  138. /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
  139. /// with the [data-val=true] attribute value and enables validation according to the data-val-*
  140. /// attribute values.
  141. /// </summary>
  142. /// <param name="selector" type="String">Any valid jQuery selector.</param>
  143. $(selector).find(":input[data-val=true]").each(function () {
  144. $jQval.unobtrusive.parseElement(this, true);
  145. });
  146. $("form").each(function () {
  147. var info = validationInfo(this);
  148. if (info) {
  149. info.attachValidation();
  150. }
  151. });
  152. }
  153. };
  154. adapters = $jQval.unobtrusive.adapters;
  155. adapters.add = function (adapterName, params, fn) {
  156. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
  157. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  158. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  159. /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
  160. /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
  161. /// mmmm is the parameter name).</param>
  162. /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
  163. /// attributes into jQuery Validate rules and/or messages.</param>
  164. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  165. if (!fn) { // Called with no params, just a function
  166. fn = params;
  167. params = [];
  168. }
  169. this.push({ name: adapterName, params: params, adapt: fn });
  170. return this;
  171. };
  172. adapters.addBool = function (adapterName, ruleName) {
  173. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  174. /// the jQuery Validate validation rule has no parameter values.</summary>
  175. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  176. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  177. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  178. /// of adapterName will be used instead.</param>
  179. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  180. return this.add(adapterName, function (options) {
  181. setValidationValues(options, ruleName || adapterName, true);
  182. });
  183. };
  184. adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
  185. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  186. /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
  187. /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
  188. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  189. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  190. /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  191. /// have a minimum value.</param>
  192. /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  193. /// have a maximum value.</param>
  194. /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
  195. /// have both a minimum and maximum value.</param>
  196. /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  197. /// contains the minimum value. The default is "min".</param>
  198. /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  199. /// contains the maximum value. The default is "max".</param>
  200. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  201. return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
  202. var min = options.params.min,
  203. max = options.params.max;
  204. if (min && max) {
  205. setValidationValues(options, minMaxRuleName, [min, max]);
  206. }
  207. else if (min) {
  208. setValidationValues(options, minRuleName, min);
  209. }
  210. else if (max) {
  211. setValidationValues(options, maxRuleName, max);
  212. }
  213. });
  214. };
  215. adapters.addSingleVal = function (adapterName, attribute, ruleName) {
  216. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  217. /// the jQuery Validate validation rule has a single value.</summary>
  218. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  219. /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
  220. /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
  221. /// The default is "val".</param>
  222. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  223. /// of adapterName will be used instead.</param>
  224. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  225. return this.add(adapterName, [attribute || "val"], function (options) {
  226. setValidationValues(options, ruleName || adapterName, options.params[attribute]);
  227. });
  228. };
  229. $jQval.addMethod("__dummy__", function (value, element, params) {
  230. return true;
  231. });
  232. $jQval.addMethod("regex", function (value, element, params) {
  233. var match;
  234. if (this.optional(element)) {
  235. return true;
  236. }
  237. match = new RegExp(params).exec(value);
  238. return (match && (match.index === 0) && (match[0].length === value.length));
  239. });
  240. adapters.addSingleVal("accept", "exts").addSingleVal("regex", "pattern");
  241. adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
  242. adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
  243. adapters.add("equalto", ["other"], function (options) {
  244. var prefix = getModelPrefix(options.element.name),
  245. other = options.params.other,
  246. fullOtherName = appendModelPrefix(other, prefix),
  247. element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];
  248. setValidationValues(options, "equalTo", element);
  249. });
  250. adapters.add("required", function (options) {
  251. // jQuery Validate equates "required" with "mandatory" for checkbox elements
  252. if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
  253. setValidationValues(options, "required", true);
  254. }
  255. });
  256. adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
  257. var value = {
  258. url: options.params.url,
  259. type: options.params.type || "GET",
  260. data: {}
  261. },
  262. prefix = getModelPrefix(options.element.name);
  263. $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
  264. var paramName = appendModelPrefix(fieldName, prefix);
  265. value.data[paramName] = function () {
  266. return $(options.form).find(":input[name='" + paramName + "']").val();
  267. };
  268. });
  269. setValidationValues(options, "remote", value);
  270. });
  271. $(function () {
  272. $jQval.unobtrusive.parse(document);
  273. });
  274. }(jQuery));