jquery.validate.unobtrusive.js 19 KB

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