1 /* NUGET: BEGIN LICENSE TEXT
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.
14 * NUGET: END LICENSE TEXT */
16 ** Unobtrusive validation support library for jQuery and jQuery Validate
17 ** Copyright (C) Microsoft Corporation. All rights reserved.
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 */
24 var $jQval = $.validator,
26 data_validation = "unobtrusiveValidation";
28 function setValidationValues(options, ruleName, value) {
29 options.rules[ruleName] = value;
30 if (options.message) {
31 options.messages[ruleName] = options.message;
35 function splitAndTrim(value) {
36 return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
39 function escapeAttributeValue(value) {
40 // As mentioned on http://api.jquery.com/category/selectors/
41 return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
44 function getModelPrefix(fieldName) {
45 return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
48 function appendModelPrefix(value, prefix) {
49 if (value.indexOf("*.") === 0) {
50 value = value.replace("*.", prefix);
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;
60 container.removeClass("field-validation-valid").addClass("field-validation-error");
61 error.data("unobtrusiveContainer", container);
65 error.removeClass("input-validation-error").appendTo(container);
72 function onErrors(event, validator) { // 'this' is the form element
73 var container = $(this).find("[data-valmsg-summary=true]"),
74 list = container.find("ul");
76 if (list && list.length && validator.errorList.length) {
78 container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
80 $.each(validator.errorList, function () {
81 $("<li />").html(this.message).appendTo(list);
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;
92 container.addClass("field-validation-valid").removeClass("field-validation-error");
93 error.removeData("unobtrusiveContainer");
101 function onReset(event) { // 'this' is the form element
103 key = '__jquery_unobtrusive_validation_form_reset';
104 if ($form.data(key)) {
107 // Set a flag that indicates we're currently resetting the form.
108 $form.data(key, true);
110 $form.data("validator").resetForm();
112 $form.removeData(key);
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");
126 function validationInfo(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);
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);
145 invalidHandler: function () {
146 onErrors.apply(form, arguments);
147 execInContext("invalidHandler", arguments);
151 success: function () {
152 onSuccess.apply(form, arguments);
153 execInContext("success", arguments);
156 attachValidation: function () {
158 .off("reset." + data_validation, onResetProxy)
159 .on("reset." + data_validation, onResetProxy)
160 .validate(this.options);
162 validate: function () { // a validation function that is called by unobtrusive Ajax
164 return $form.valid();
167 $form.data(data_validation, result);
173 $jQval.unobtrusive = {
176 parseElement: function (element, skipAttach) {
178 /// Parses a single HTML element for unobtrusive validation attributes.
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;
189 if (!form) { // Cannot do client-side validation without a form
193 valInfo = validationInfo(form);
194 valInfo.options.rules[element.name] = rules = {};
195 valInfo.options.messages[element.name] = messages = {};
197 $.each(this.adapters, function () {
198 var prefix = "data-val-" + this.name,
199 message = $element.attr(prefix),
202 if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
205 $.each(this.params, function () {
206 paramValues[this] = $element.attr(prefix + this);
220 $.extend(rules, { "__dummy__": true });
223 valInfo.attachValidation();
227 parse: function (selector) {
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.
233 /// <param name="selector" type="String">Any valid jQuery selector.</param>
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()
241 .add($selector.find("form"))
242 .has("[data-val=true]");
244 $selector.find("[data-val=true]").each(function () {
245 $jQval.unobtrusive.parseElement(this, true);
248 $forms.each(function () {
249 var info = validationInfo(this);
251 info.attachValidation();
257 adapters = $jQval.unobtrusive.adapters;
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
273 this.push({ name: adapterName, params: params, adapt: fn });
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);
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;
312 setValidationValues(options, minMaxRuleName, [min, max]);
315 setValidationValues(options, minRuleName, min);
318 setValidationValues(options, maxRuleName, max);
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]);
338 $jQval.addMethod("__dummy__", function (value, element, params) {
342 $jQval.addMethod("regex", function (value, element, params) {
344 if (this.optional(element)) {
348 match = new RegExp(params).exec(value);
349 return (match && (match.index === 0) && (match[0].length === value.length));
352 $jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
355 match = value.match(/\W/g);
356 match = match && match.length >= nonalphamin;
361 if ($jQval.methods.extension) {
362 adapters.addSingleVal("accept", "mimtype");
363 adapters.addSingleVal("extension", "extension");
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");
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];
381 setValidationValues(options, "equalTo", element);
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);
389 adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
391 url: options.params.url,
392 type: options.params.type || "GET",
395 prefix = getModelPrefix(options.element.name);
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() || '';
405 else if (field.is(":radio")) {
406 return field.filter(":checked").val() || '';
412 setValidationValues(options, "remote", value);
414 adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
415 if (options.params.min) {
416 setValidationValues(options, "minlength", options.params.min);
418 if (options.params.nonalphamin) {
419 setValidationValues(options, "nonalphamin", options.params.nonalphamin);
421 if (options.params.regex) {
422 setValidationValues(options, "regex", options.params.regex);
427 $jQval.unobtrusive.parse(document);