jquery.validate.unobtrusive.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. debugger
  114. var prefix = "data-val-" + this.name,
  115. message = $element.attr(prefix),
  116. paramValues = {};
  117. if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
  118. prefix += "-";
  119. $.each(this.params, function () {
  120. paramValues[this] = $element.attr(prefix + this);
  121. });
  122. this.adapt({
  123. element: element,
  124. form: form,
  125. message: message,
  126. params: paramValues,
  127. rules: rules,
  128. messages: messages
  129. });
  130. }
  131. });
  132. jQuery.extend(rules, { "__dummy__": true });
  133. if (!skipAttach) {
  134. valInfo.attachValidation();
  135. }
  136. },
  137. parse: function (selector) {
  138. /// <summary>
  139. /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
  140. /// with the [data-val=true] attribute value and enables validation according to the data-val-*
  141. /// attribute values.
  142. /// </summary>
  143. /// <param name="selector" type="String">Any valid jQuery selector.</param>
  144. $(selector).find(":input[data-val=true]").each(function () {
  145. $jQval.unobtrusive.parseElement(this, true);
  146. });
  147. $("form").each(function () {
  148. var info = validationInfo(this);
  149. if (info) {
  150. info.attachValidation();
  151. }
  152. });
  153. }
  154. };
  155. adapters = $jQval.unobtrusive.adapters;
  156. adapters.add = function (adapterName, params, fn) {
  157. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
  158. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  159. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  160. /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
  161. /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
  162. /// mmmm is the parameter name).</param>
  163. /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
  164. /// attributes into jQuery Validate rules and/or messages.</param>
  165. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  166. if (!fn) { // Called with no params, just a function
  167. fn = params;
  168. params = [];
  169. }
  170. this.push({ name: adapterName, params: params, adapt: fn });
  171. return this;
  172. };
  173. adapters.addBool = function (adapterName, ruleName) {
  174. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  175. /// the jQuery Validate validation rule has no parameter values.</summary>
  176. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  177. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  178. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  179. /// of adapterName will be used instead.</param>
  180. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  181. return this.add(adapterName, function (options) {
  182. setValidationValues(options, ruleName || adapterName, true);
  183. });
  184. };
  185. adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
  186. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  187. /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
  188. /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
  189. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  190. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  191. /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  192. /// have a minimum value.</param>
  193. /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  194. /// have a maximum value.</param>
  195. /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
  196. /// have both a minimum and maximum value.</param>
  197. /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  198. /// contains the minimum value. The default is "min".</param>
  199. /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  200. /// contains the maximum value. The default is "max".</param>
  201. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  202. return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
  203. var min = options.params.min,
  204. max = options.params.max;
  205. if (min && max) {
  206. setValidationValues(options, minMaxRuleName, [min, max]);
  207. }
  208. else if (min) {
  209. setValidationValues(options, minRuleName, min);
  210. }
  211. else if (max) {
  212. setValidationValues(options, maxRuleName, max);
  213. }
  214. });
  215. };
  216. adapters.addSingleVal = function (adapterName, attribute, ruleName) {
  217. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  218. /// the jQuery Validate validation rule has a single value.</summary>
  219. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  220. /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
  221. /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
  222. /// The default is "val".</param>
  223. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  224. /// of adapterName will be used instead.</param>
  225. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  226. return this.add(adapterName, [attribute || "val"], function (options) {
  227. setValidationValues(options, ruleName || adapterName, options.params[attribute]);
  228. });
  229. };
  230. $jQval.addMethod("__dummy__", function (value, element, params) {
  231. return true;
  232. });
  233. $jQval.addMethod("regex", function (value, element, params) {
  234. var match;
  235. if (this.optional(element)) {
  236. return true;
  237. }
  238. match = new RegExp(params).exec(value);
  239. return (match && (match.index === 0) && (match[0].length === value.length));
  240. });
  241. adapters.addSingleVal("accept", "exts").addSingleVal("regex", "pattern");
  242. adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
  243. adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
  244. adapters.add("equalto", ["other"], function (options) {
  245. var prefix = getModelPrefix(options.element.name),
  246. other = options.params.other,
  247. fullOtherName = appendModelPrefix(other, prefix),
  248. element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];
  249. setValidationValues(options, "equalTo", element);
  250. });
  251. adapters.add("required", function (options) {
  252. // jQuery Validate equates "required" with "mandatory" for checkbox elements
  253. if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
  254. setValidationValues(options, "required", true);
  255. }
  256. });
  257. adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
  258. var value = {
  259. url: options.params.url,
  260. type: options.params.type || "GET",
  261. data: {}
  262. },
  263. prefix = getModelPrefix(options.element.name);
  264. $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
  265. var paramName = appendModelPrefix(fieldName, prefix);
  266. value.data[paramName] = function () {
  267. return $(options.form).find(":input[name='" + paramName + "']").val();
  268. };
  269. });
  270. setValidationValues(options, "remote", value);
  271. });
  272. $(function () {
  273. $jQval.unobtrusive.parse(document);
  274. });
  275. }(jQuery));