jquery.validate.unobtrusive.js 16 KB

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