source: PostgreSqlDotnetCore/wwwroot/js/jquery.validate.unobtrusive.js@ 8f8226c

main
Last change on this file since 8f8226c was 2aea0fd, checked in by ElenaMoskova <elena.moskova99@…>, 4 months ago

init commit Elena

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