jquery.validate.unobtrusive.js 16 KB

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