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