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