jquery.validate.unobtrusive.js 19 KB

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