jquery.validate.unobtrusive.js 19 KB

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