jquery.validate.unobtrusive_customer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /// <reference path="jquery-1.4.4.js" />
  2. /// <reference path="jquery.validate.js" />
  3. /*!
  4. ** Unobtrusive validation support library for jQuery and jQuery Validate
  5. ** Copyright (C) Microsoft Corporation. All rights reserved.
  6. */
  7. /*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 */
  8. /*global document: false, jQuery: false */
  9. (function ($) {
  10. var $jQval = $.validator,
  11. adapters,
  12. data_validation = "unobtrusiveValidation";
  13. function setValidationValues(options, ruleName, value) {
  14. options.rules[ruleName] = value;
  15. if (options.message) {
  16. options.messages[ruleName] = options.message;
  17. }
  18. }
  19. function splitAndTrim(value) {
  20. return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
  21. }
  22. function getModelPrefix(fieldName) {
  23. return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
  24. }
  25. function appendModelPrefix(value, prefix) {
  26. if (value.indexOf("*.") === 0) {
  27. value = value.replace("*.", prefix);
  28. }
  29. return value;
  30. }
  31. //2014.05.28 Add with Peter begin
  32. function CPos(left, top) {
  33. this.left = left;
  34. this.top = top;
  35. }
  36. function GetObjPos(ATarget) {
  37. var target = ATarget;
  38. var pos = new CPos(target.offsetLeft, target.offsetTop);
  39. var target = target.offsetParent;
  40. while (target) {
  41. pos.left += target.offsetLeft;
  42. pos.top += target.offsetTop;
  43. target = target.offsetParent
  44. }
  45. return pos;
  46. }
  47. //2014.05.28 Add with Peter end
  48. function onError(error, inputElement) { // 'this' is the form element
  49. var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
  50. replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
  51. container.removeClass("field-validation-valid").addClass("field-validation-error");
  52. error.data("unobtrusiveContainer", container);
  53. //2014.05.28 Add with Peter
  54. var pos = GetObjPos(inputElement[0]);
  55. if (error.text().length > 0) {
  56. if ($("[popupfor='" + inputElement[0].name + "']").length == 0) {
  57. $(document.body).append("<div class=\"poptip\" popupfor=\"" + inputElement[0].name + "\" style=\"top: " + (pos.top + inputElement.height()) + "px;left:" + pos.left + "px;\"><span class=\"poptip-arrow poptip-arrow-top\"><em>◆</em><i>◆</i></span>" + error.text() + "</div>");
  58. }
  59. else {
  60. $("[popupfor='" + inputElement[0].name + "']").contents().filter(function () {
  61. return this.nodeType == 3;
  62. }).replaceWith(error.text());
  63. }
  64. $("div[popupfor='" + inputElement[0].name + "']").show();
  65. }
  66. else {
  67. $("div[popupfor='" + inputElement[0].name + "']").hide();
  68. }
  69. //End
  70. if (replace) {
  71. container.empty();
  72. error.removeClass("input-validation-error").appendTo(container);
  73. }
  74. else {
  75. error.hide();
  76. }
  77. }
  78. function onErrors(form, validator) { // 'this' is the form element
  79. var container = $(this).find("[data-valmsg-summary=true]"),
  80. list = container.find("ul");
  81. if (list && list.length && validator.errorList.length) {
  82. list.empty();
  83. container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
  84. $.each(validator.errorList, function () {
  85. $("<li />").html(this.message).appendTo(list);
  86. });
  87. }
  88. }
  89. function onSuccess(error) { // 'this' is the form element
  90. var container = error.data("unobtrusiveContainer"),
  91. replace = $.parseJSON(container.attr("data-valmsg-replace"));
  92. if (container) {
  93. container.addClass("field-validation-valid").removeClass("field-validation-error");
  94. error.removeData("unobtrusiveContainer");
  95. if (replace) {
  96. container.empty();
  97. }
  98. }
  99. }
  100. function validationInfo(form) {
  101. var $form = $(form),
  102. result = $form.data(data_validation);
  103. if (!result) {
  104. result = {
  105. options: { // options structure passed to jQuery Validate's validate() method
  106. errorClass: "input-validation-error",
  107. errorElement: "span",
  108. errorPlacement: $.proxy(onError, form),
  109. invalidHandler: $.proxy(onErrors, form),
  110. messages: {},
  111. rules: {},
  112. success: $.proxy(onSuccess, form)
  113. },
  114. attachValidation: function () {
  115. $form.validate(this.options);
  116. },
  117. validate: function () { // a validation function that is called by unobtrusive Ajax
  118. $form.validate();
  119. return $form.valid();
  120. }
  121. };
  122. $form.data(data_validation, result);
  123. }
  124. return result;
  125. }
  126. $jQval.unobtrusive = {
  127. adapters: [],
  128. parseElement: function (element, skipAttach) {
  129. /// <summary>
  130. /// Parses a single HTML element for unobtrusive validation attributes.
  131. /// </summary>
  132. /// <param name="element" domElement="true">The HTML element to be parsed.</param>
  133. /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
  134. /// validation to the form. If parsing just this single element, you should specify true.
  135. /// If parsing several elements, you should specify false, and manually attach the validation
  136. /// to the form when you are finished. The default is false.</param>
  137. var $element = $(element),
  138. form = $element.parents("form")[0],
  139. valInfo, rules, messages;
  140. if (!form) { // Cannot do client-side validation without a form
  141. return;
  142. }
  143. valInfo = validationInfo(form);
  144. valInfo.options.rules[element.name] = rules = {};
  145. valInfo.options.messages[element.name] = messages = {};
  146. $.each(this.adapters, function () {
  147. var prefix = "data-val-" + this.name,
  148. message = $element.attr(prefix),
  149. paramValues = {};
  150. if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
  151. prefix += "-";
  152. $.each(this.params, function () {
  153. paramValues[this] = $element.attr(prefix + this);
  154. });
  155. this.adapt({
  156. element: element,
  157. form: form,
  158. message: message,
  159. params: paramValues,
  160. rules: rules,
  161. messages: messages
  162. });
  163. }
  164. });
  165. jQuery.extend(rules, { "__dummy__": true });
  166. if (!skipAttach) {
  167. valInfo.attachValidation();
  168. }
  169. },
  170. parse: function (selector) {
  171. /// <summary>
  172. /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
  173. /// with the [data-val=true] attribute value and enables validation according to the data-val-*
  174. /// attribute values.
  175. /// </summary>
  176. /// <param name="selector" type="String">Any valid jQuery selector.</param>
  177. $(selector).find(":input[data-val=true]").each(function () {
  178. $jQval.unobtrusive.parseElement(this, true);
  179. });
  180. $("form").each(function () {
  181. var info = validationInfo(this);
  182. if (info) {
  183. info.attachValidation();
  184. }
  185. });
  186. }
  187. };
  188. adapters = $jQval.unobtrusive.adapters;
  189. adapters.add = function (adapterName, params, fn) {
  190. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
  191. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  192. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  193. /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
  194. /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
  195. /// mmmm is the parameter name).</param>
  196. /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
  197. /// attributes into jQuery Validate rules and/or messages.</param>
  198. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  199. if (!fn) { // Called with no params, just a function
  200. fn = params;
  201. params = [];
  202. }
  203. this.push({ name: adapterName, params: params, adapt: fn });
  204. return this;
  205. };
  206. adapters.addBool = function (adapterName, ruleName) {
  207. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  208. /// the jQuery Validate validation rule has no parameter values.</summary>
  209. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  210. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  211. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  212. /// of adapterName will be used instead.</param>
  213. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  214. return this.add(adapterName, function (options) {
  215. setValidationValues(options, ruleName || adapterName, true);
  216. });
  217. };
  218. adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
  219. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  220. /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
  221. /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
  222. /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
  223. /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
  224. /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  225. /// have a minimum value.</param>
  226. /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
  227. /// have a maximum value.</param>
  228. /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
  229. /// have both a minimum and maximum value.</param>
  230. /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  231. /// contains the minimum value. The default is "min".</param>
  232. /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
  233. /// contains the maximum value. The default is "max".</param>
  234. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  235. return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
  236. var min = options.params.min,
  237. max = options.params.max;
  238. if (min && max) {
  239. setValidationValues(options, minMaxRuleName, [min, max]);
  240. }
  241. else if (min) {
  242. setValidationValues(options, minRuleName, min);
  243. }
  244. else if (max) {
  245. setValidationValues(options, maxRuleName, max);
  246. }
  247. });
  248. };
  249. adapters.addSingleVal = function (adapterName, attribute, ruleName) {
  250. /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
  251. /// the jQuery Validate validation rule has a single value.</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="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
  255. /// The default is "val".</param>
  256. /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
  257. /// of adapterName will be used instead.</param>
  258. /// <returns type="jQuery.validator.unobtrusive.adapters" />
  259. return this.add(adapterName, [attribute || "val"], function (options) {
  260. setValidationValues(options, ruleName || adapterName, options.params[attribute]);
  261. });
  262. };
  263. $jQval.addMethod("__dummy__", function (value, element, params) {
  264. return true;
  265. });
  266. $jQval.addMethod("regex", function (value, element, params) {
  267. var match;
  268. if (this.optional(element)) {
  269. return true;
  270. }
  271. match = new RegExp(params).exec(value);
  272. return (match && (match.index === 0) && (match[0].length === value.length));
  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=" + 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='" + paramName + "']").val();
  301. };
  302. });
  303. setValidationValues(options, "remote", value);
  304. });
  305. $(function () {
  306. $jQval.unobtrusive.parse(document);
  307. });
  308. } (jQuery));