modify copyright year
[msb/discovery.git] / discovery-ui / src / main / resources / iui / microservices / js / jquery-validation / additional-methods.js
1 /*
2  * Copyright 2016-2017 ZTE, Inc. and others.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 (function( factory ) {
17         if ( typeof define === "function" && define.amd ) {
18                 define( ["jquery", "./jquery.validate"], factory );
19         } else {
20                 factory( jQuery );
21         }
22 }(function( $ ) {
23
24 (function() {
25
26         function stripHtml(value) {
27                 // remove html tags and space chars
28                 return value.replace(/<.[^<>]*?>/g, " ").replace(/&nbsp;|&#160;/gi, " ")
29                 // remove punctuation
30                 .replace(/[.(),;:!?%#$'\"_+=\/\-“”’]*/g, "");
31         }
32
33         $.validator.addMethod("maxWords", function(value, element, params) {
34                 return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length <= params;
35         }, $.validator.format("Please enter {0} words or less."));
36
37         $.validator.addMethod("minWords", function(value, element, params) {
38                 return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params;
39         }, $.validator.format("Please enter at least {0} words."));
40
41         $.validator.addMethod("rangeWords", function(value, element, params) {
42                 var valueStripped = stripHtml(value),
43                         regex = /\b\w+\b/g;
44                 return this.optional(element) || valueStripped.match(regex).length >= params[0] && valueStripped.match(regex).length <= params[1];
45         }, $.validator.format("Please enter between {0} and {1} words."));
46
47 }());
48
49 // Accept a value from a file input based on a required mimetype
50 $.validator.addMethod("accept", function(value, element, param) {
51         // Split mime on commas in case we have multiple types we can accept
52         var typeParam = typeof param === "string" ? param.replace(/\s/g, "").replace(/,/g, "|") : "image/*",
53         optionalValue = this.optional(element),
54         i, file;
55
56         // Element is optional
57         if (optionalValue) {
58                 return optionalValue;
59         }
60
61         if ($(element).attr("type") === "file") {
62                 // If we are using a wildcard, make it regex friendly
63                 typeParam = typeParam.replace(/\*/g, ".*");
64
65                 // Check if the element has a FileList before checking each file
66                 if (element.files && element.files.length) {
67                         for (i = 0; i < element.files.length; i++) {
68                                 file = element.files[i];
69
70                                 // Grab the mimetype from the loaded file, verify it matches
71                                 if (!file.type.match(new RegExp( ".?(" + typeParam + ")$", "i"))) {
72                                         return false;
73                                 }
74                         }
75                 }
76         }
77
78         // Either return true because we've validated each file, or because the
79         // browser does not support element.files and the FileList feature
80         return true;
81 }, $.validator.format("Please enter a value with a valid mimetype."));
82
83 $.validator.addMethod("alphanumeric", function(value, element) {
84         return this.optional(element) || /^\w+$/i.test(value);
85 }, "Letters, numbers, and underscores only please");
86
87 /*
88  * Dutch bank account numbers (not 'giro' numbers) have 9 digits
89  * and pass the '11 check'.
90  * We accept the notation with spaces, as that is common.
91  * acceptable: 123456789 or 12 34 56 789
92  */
93 $.validator.addMethod("bankaccountNL", function(value, element) {
94         if (this.optional(element)) {
95                 return true;
96         }
97         if (!(/^[0-9]{9}|([0-9]{2} ){3}[0-9]{3}$/.test(value))) {
98                 return false;
99         }
100         // now '11 check'
101         var account = value.replace(/ /g, ""), // remove spaces
102                 sum = 0,
103                 len = account.length,
104                 pos, factor, digit;
105         for ( pos = 0; pos < len; pos++ ) {
106                 factor = len - pos;
107                 digit = account.substring(pos, pos + 1);
108                 sum = sum + factor * digit;
109         }
110         return sum % 11 === 0;
111 }, "Please specify a valid bank account number");
112
113 $.validator.addMethod("bankorgiroaccountNL", function(value, element) {
114         return this.optional(element) ||
115                         ($.validator.methods.bankaccountNL.call(this, value, element)) ||
116                         ($.validator.methods.giroaccountNL.call(this, value, element));
117 }, "Please specify a valid bank or giro account number");
118
119 /**
120  * BIC is the business identifier code (ISO 9362). This BIC check is not a guarantee for authenticity.
121  *
122  * BIC pattern: BBBBCCLLbbb (8 or 11 characters long; bbb is optional)
123  *
124  * BIC definition in detail:
125  * - First 4 characters - bank code (only letters)
126  * - Next 2 characters - ISO 3166-1 alpha-2 country code (only letters)
127  * - Next 2 characters - location code (letters and digits)
128  *   a. shall not start with '0' or '1'
129  *   b. second character must be a letter ('O' is not allowed) or one of the following digits ('0' for test (therefore not allowed), '1' for passive participant and '2' for active participant)
130  * - Last 3 characters - branch code, optional (shall not start with 'X' except in case of 'XXX' for primary office) (letters and digits)
131  */
132 $.validator.addMethod("bic", function(value, element) {
133     return this.optional( element ) || /^([A-Z]{6}[A-Z2-9][A-NP-Z1-2])(X{3}|[A-WY-Z0-9][A-Z0-9]{2})?$/.test( value );
134 }, "Please specify a valid BIC code");
135
136 /*
137  * Código de identificación fiscal ( CIF ) is the tax identification code for Spanish legal entities
138  * Further rules can be found in Spanish on http://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal
139  */
140 $.validator.addMethod( "cifES", function( value ) {
141         "use strict";
142
143         var num = [],
144                 controlDigit, sum, i, count, tmp, secondDigit;
145
146         value = value.toUpperCase();
147
148         // Quick format test
149         if ( !value.match( "((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)" ) ) {
150                 return false;
151         }
152
153         for ( i = 0; i < 9; i++ ) {
154                 num[ i ] = parseInt( value.charAt( i ), 10 );
155         }
156
157         // Algorithm for checking CIF codes
158         sum = num[ 2 ] + num[ 4 ] + num[ 6 ];
159         for ( count = 1; count < 8; count += 2 ) {
160                 tmp = ( 2 * num[ count ] ).toString();
161                 secondDigit = tmp.charAt( 1 );
162
163                 sum += parseInt( tmp.charAt( 0 ), 10 ) + ( secondDigit === "" ? 0 : parseInt( secondDigit, 10 ) );
164         }
165
166         /* The first (position 1) is a letter following the following criteria:
167          *      A. Corporations
168          *      B. LLCs
169          *      C. General partnerships
170          *      D. Companies limited partnerships
171          *      E. Communities of goods
172          *      F. Cooperative Societies
173          *      G. Associations
174          *      H. Communities of homeowners in horizontal property regime
175          *      J. Civil Societies
176          *      K. Old format
177          *      L. Old format
178          *      M. Old format
179          *      N. Nonresident entities
180          *      P. Local authorities
181          *      Q. Autonomous bodies, state or not, and the like, and congregations and religious institutions
182          *      R. Congregations and religious institutions (since 2008 ORDER EHA/451/2008)
183          *      S. Organs of State Administration and regions
184          *      V. Agrarian Transformation
185          *      W. Permanent establishments of non-resident in Spain
186          */
187         if ( /^[ABCDEFGHJNPQRSUVW]{1}/.test( value ) ) {
188                 sum += "";
189                 controlDigit = 10 - parseInt( sum.charAt( sum.length - 1 ), 10 );
190                 value += controlDigit;
191                 return ( num[ 8 ].toString() === String.fromCharCode( 64 + controlDigit ) || num[ 8 ].toString() === value.charAt( value.length - 1 ) );
192         }
193
194         return false;
195
196 }, "Please specify a valid CIF number." );
197
198 /* NOTICE: Modified version of Castle.Components.Validator.CreditCardValidator
199  * Redistributed under the the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0
200  * Valid Types: mastercard, visa, amex, dinersclub, enroute, discover, jcb, unknown, all (overrides all other settings)
201  */
202 $.validator.addMethod("creditcardtypes", function(value, element, param) {
203         if (/[^0-9\-]+/.test(value)) {
204                 return false;
205         }
206
207         value = value.replace(/\D/g, "");
208
209         var validTypes = 0x0000;
210
211         if (param.mastercard) {
212                 validTypes |= 0x0001;
213         }
214         if (param.visa) {
215                 validTypes |= 0x0002;
216         }
217         if (param.amex) {
218                 validTypes |= 0x0004;
219         }
220         if (param.dinersclub) {
221                 validTypes |= 0x0008;
222         }
223         if (param.enroute) {
224                 validTypes |= 0x0010;
225         }
226         if (param.discover) {
227                 validTypes |= 0x0020;
228         }
229         if (param.jcb) {
230                 validTypes |= 0x0040;
231         }
232         if (param.unknown) {
233                 validTypes |= 0x0080;
234         }
235         if (param.all) {
236                 validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080;
237         }
238         if (validTypes & 0x0001 && /^(5[12345])/.test(value)) { //mastercard
239                 return value.length === 16;
240         }
241         if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
242                 return value.length === 16;
243         }
244         if (validTypes & 0x0004 && /^(3[47])/.test(value)) { //amex
245                 return value.length === 15;
246         }
247         if (validTypes & 0x0008 && /^(3(0[012345]|[68]))/.test(value)) { //dinersclub
248                 return value.length === 14;
249         }
250         if (validTypes & 0x0010 && /^(2(014|149))/.test(value)) { //enroute
251                 return value.length === 15;
252         }
253         if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover
254                 return value.length === 16;
255         }
256         if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb
257                 return value.length === 16;
258         }
259         if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb
260                 return value.length === 15;
261         }
262         if (validTypes & 0x0080) { //unknown
263                 return true;
264         }
265         return false;
266 }, "Please enter a valid credit card number.");
267
268 /**
269  * Validates currencies with any given symbols by @jameslouiz
270  * Symbols can be optional or required. Symbols required by default
271  *
272  * Usage examples:
273  *  currency: ["£", false] - Use false for soft currency validation
274  *  currency: ["$", false]
275  *  currency: ["RM", false] - also works with text based symbols such as "RM" - Malaysia Ringgit etc
276  *
277  *  <input class="currencyInput" name="currencyInput">
278  *
279  * Soft symbol checking
280  *  currencyInput: {
281  *     currency: ["$", false]
282  *  }
283  *
284  * Strict symbol checking (default)
285  *  currencyInput: {
286  *     currency: "$"
287  *     //OR
288  *     currency: ["$", true]
289  *  }
290  *
291  * Multiple Symbols
292  *  currencyInput: {
293  *     currency: "$,£,¢"
294  *  }
295  */
296 $.validator.addMethod("currency", function(value, element, param) {
297     var isParamString = typeof param === "string",
298         symbol = isParamString ? param : param[0],
299         soft = isParamString ? true : param[1],
300         regex;
301
302     symbol = symbol.replace(/,/g, "");
303     symbol = soft ? symbol + "]" : symbol + "]?";
304     regex = "^[" + symbol + "([1-9]{1}[0-9]{0,2}(\\,[0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)$";
305     regex = new RegExp(regex);
306     return this.optional(element) || regex.test(value);
307
308 }, "Please specify a valid currency");
309
310 $.validator.addMethod("dateFA", function(value, element) {
311         return this.optional(element) || /^[1-4]\d{3}\/((0?[1-6]\/((3[0-1])|([1-2][0-9])|(0?[1-9])))|((1[0-2]|(0?[7-9]))\/(30|([1-2][0-9])|(0?[1-9]))))$/.test(value);
312 }, "Please enter a correct date");
313
314 /**
315  * Return true, if the value is a valid date, also making this formal check dd/mm/yyyy.
316  *
317  * @example $.validator.methods.date("01/01/1900")
318  * @result true
319  *
320  * @example $.validator.methods.date("01/13/1990")
321  * @result false
322  *
323  * @example $.validator.methods.date("01.01.1900")
324  * @result false
325  *
326  * @example <input name="pippo" class="{dateITA:true}" />
327  * @desc Declares an optional input element whose value must be a valid date.
328  *
329  * @name $.validator.methods.dateITA
330  * @type Boolean
331  * @cat Plugins/Validate/Methods
332  */
333 $.validator.addMethod("dateITA", function(value, element) {
334         var check = false,
335                 re = /^\d{1,2}\/\d{1,2}\/\d{4}$/,
336                 adata, gg, mm, aaaa, xdata;
337         if ( re.test(value)) {
338                 adata = value.split("/");
339                 gg = parseInt(adata[0], 10);
340                 mm = parseInt(adata[1], 10);
341                 aaaa = parseInt(adata[2], 10);
342                 xdata = new Date(aaaa, mm - 1, gg, 12, 0, 0, 0);
343                 if ( ( xdata.getUTCFullYear() === aaaa ) && ( xdata.getUTCMonth () === mm - 1 ) && ( xdata.getUTCDate() === gg ) ) {
344                         check = true;
345                 } else {
346                         check = false;
347                 }
348         } else {
349                 check = false;
350         }
351         return this.optional(element) || check;
352 }, "Please enter a correct date");
353
354 $.validator.addMethod("dateNL", function(value, element) {
355         return this.optional(element) || /^(0?[1-9]|[12]\d|3[01])[\.\/\-](0?[1-9]|1[012])[\.\/\-]([12]\d)?(\d\d)$/.test(value);
356 }, "Please enter a correct date");
357
358 // Older "accept" file extension method. Old docs: http://docs.jquery.com/Plugins/Validation/Methods/accept
359 $.validator.addMethod("extension", function(value, element, param) {
360         param = typeof param === "string" ? param.replace(/,/g, "|") : "png|jpe?g|gif";
361         return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
362 }, $.validator.format("Please enter a value with a valid extension."));
363
364 /**
365  * Dutch giro account numbers (not bank numbers) have max 7 digits
366  */
367 $.validator.addMethod("giroaccountNL", function(value, element) {
368         return this.optional(element) || /^[0-9]{1,7}$/.test(value);
369 }, "Please specify a valid giro account number");
370
371 /**
372  * IBAN is the international bank account number.
373  * It has a country - specific format, that is checked here too
374  */
375 $.validator.addMethod("iban", function(value, element) {
376         // some quick simple tests to prevent needless work
377         if (this.optional(element)) {
378                 return true;
379         }
380
381         // remove spaces and to upper case
382         var iban = value.replace(/ /g, "").toUpperCase(),
383                 ibancheckdigits = "",
384                 leadingZeroes = true,
385                 cRest = "",
386                 cOperator = "",
387                 countrycode, ibancheck, charAt, cChar, bbanpattern, bbancountrypatterns, ibanregexp, i, p;
388
389         if (!(/^([a-zA-Z0-9]{4} ){2,8}[a-zA-Z0-9]{1,4}|[a-zA-Z0-9]{12,34}$/.test(iban))) {
390                 return false;
391         }
392
393         // check the country code and find the country specific format
394         countrycode = iban.substring(0, 2);
395         bbancountrypatterns = {
396                 "AL": "\\d{8}[\\dA-Z]{16}",
397                 "AD": "\\d{8}[\\dA-Z]{12}",
398                 "AT": "\\d{16}",
399                 "AZ": "[\\dA-Z]{4}\\d{20}",
400                 "BE": "\\d{12}",
401                 "BH": "[A-Z]{4}[\\dA-Z]{14}",
402                 "BA": "\\d{16}",
403                 "BR": "\\d{23}[A-Z][\\dA-Z]",
404                 "BG": "[A-Z]{4}\\d{6}[\\dA-Z]{8}",
405                 "CR": "\\d{17}",
406                 "HR": "\\d{17}",
407                 "CY": "\\d{8}[\\dA-Z]{16}",
408                 "CZ": "\\d{20}",
409                 "DK": "\\d{14}",
410                 "DO": "[A-Z]{4}\\d{20}",
411                 "EE": "\\d{16}",
412                 "FO": "\\d{14}",
413                 "FI": "\\d{14}",
414                 "FR": "\\d{10}[\\dA-Z]{11}\\d{2}",
415                 "GE": "[\\dA-Z]{2}\\d{16}",
416                 "DE": "\\d{18}",
417                 "GI": "[A-Z]{4}[\\dA-Z]{15}",
418                 "GR": "\\d{7}[\\dA-Z]{16}",
419                 "GL": "\\d{14}",
420                 "GT": "[\\dA-Z]{4}[\\dA-Z]{20}",
421                 "HU": "\\d{24}",
422                 "IS": "\\d{22}",
423                 "IE": "[\\dA-Z]{4}\\d{14}",
424                 "IL": "\\d{19}",
425                 "IT": "[A-Z]\\d{10}[\\dA-Z]{12}",
426                 "KZ": "\\d{3}[\\dA-Z]{13}",
427                 "KW": "[A-Z]{4}[\\dA-Z]{22}",
428                 "LV": "[A-Z]{4}[\\dA-Z]{13}",
429                 "LB": "\\d{4}[\\dA-Z]{20}",
430                 "LI": "\\d{5}[\\dA-Z]{12}",
431                 "LT": "\\d{16}",
432                 "LU": "\\d{3}[\\dA-Z]{13}",
433                 "MK": "\\d{3}[\\dA-Z]{10}\\d{2}",
434                 "MT": "[A-Z]{4}\\d{5}[\\dA-Z]{18}",
435                 "MR": "\\d{23}",
436                 "MU": "[A-Z]{4}\\d{19}[A-Z]{3}",
437                 "MC": "\\d{10}[\\dA-Z]{11}\\d{2}",
438                 "MD": "[\\dA-Z]{2}\\d{18}",
439                 "ME": "\\d{18}",
440                 "NL": "[A-Z]{4}\\d{10}",
441                 "NO": "\\d{11}",
442                 "PK": "[\\dA-Z]{4}\\d{16}",
443                 "PS": "[\\dA-Z]{4}\\d{21}",
444                 "PL": "\\d{24}",
445                 "PT": "\\d{21}",
446                 "RO": "[A-Z]{4}[\\dA-Z]{16}",
447                 "SM": "[A-Z]\\d{10}[\\dA-Z]{12}",
448                 "SA": "\\d{2}[\\dA-Z]{18}",
449                 "RS": "\\d{18}",
450                 "SK": "\\d{20}",
451                 "SI": "\\d{15}",
452                 "ES": "\\d{20}",
453                 "SE": "\\d{20}",
454                 "CH": "\\d{5}[\\dA-Z]{12}",
455                 "TN": "\\d{20}",
456                 "TR": "\\d{5}[\\dA-Z]{17}",
457                 "AE": "\\d{3}\\d{16}",
458                 "GB": "[A-Z]{4}\\d{14}",
459                 "VG": "[\\dA-Z]{4}\\d{16}"
460         };
461
462         bbanpattern = bbancountrypatterns[countrycode];
463         // As new countries will start using IBAN in the
464         // future, we only check if the countrycode is known.
465         // This prevents false negatives, while almost all
466         // false positives introduced by this, will be caught
467         // by the checksum validation below anyway.
468         // Strict checking should return FALSE for unknown
469         // countries.
470         if (typeof bbanpattern !== "undefined") {
471                 ibanregexp = new RegExp("^[A-Z]{2}\\d{2}" + bbanpattern + "$", "");
472                 if (!(ibanregexp.test(iban))) {
473                         return false; // invalid country specific format
474                 }
475         }
476
477         // now check the checksum, first convert to digits
478         ibancheck = iban.substring(4, iban.length) + iban.substring(0, 4);
479         for (i = 0; i < ibancheck.length; i++) {
480                 charAt = ibancheck.charAt(i);
481                 if (charAt !== "0") {
482                         leadingZeroes = false;
483                 }
484                 if (!leadingZeroes) {
485                         ibancheckdigits += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(charAt);
486                 }
487         }
488
489         // calculate the result of: ibancheckdigits % 97
490         for (p = 0; p < ibancheckdigits.length; p++) {
491                 cChar = ibancheckdigits.charAt(p);
492                 cOperator = "" + cRest + "" + cChar;
493                 cRest = cOperator % 97;
494         }
495         return cRest === 1;
496 }, "Please specify a valid IBAN");
497
498 $.validator.addMethod("integer", function(value, element) {
499         return this.optional(element) || /^-?\d+$/.test(value);
500 }, "A positive or negative non-decimal number please");
501
502 $.validator.addMethod("ipv4", function(value, element) {
503         return this.optional(element) || /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/i.test(value);
504 }, "Please enter a valid IP v4 address.");
505
506 $.validator.addMethod("ipv6", function(value, element) {
507         return this.optional(element) || /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/i.test(value);
508 }, "Please enter a valid IP v6 address.");
509
510 $.validator.addMethod("lettersonly", function(value, element) {
511         return this.optional(element) || /^[a-z]+$/i.test(value);
512 }, "Letters only please");
513
514 $.validator.addMethod("letterswithbasicpunc", function(value, element) {
515         return this.optional(element) || /^[a-z\-.,()'"\s]+$/i.test(value);
516 }, "Letters or punctuation only please");
517
518 $.validator.addMethod("mobileNL", function(value, element) {
519         return this.optional(element) || /^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)6((\s|\s?\-\s?)?[0-9]){8}$/.test(value);
520 }, "Please specify a valid mobile number");
521
522 /* For UK phone functions, do the following server side processing:
523  * Compare original input with this RegEx pattern:
524  * ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$
525  * Extract $1 and set $prefix to '+44<space>' if $1 is '44', otherwise set $prefix to '0'
526  * Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2.
527  * A number of very detailed GB telephone number RegEx patterns can also be found at:
528  * http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers
529  */
530 $.validator.addMethod("mobileUK", function(phone_number, element) {
531         phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
532         return this.optional(element) || phone_number.length > 9 &&
533                 phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?|0)7(?:[1345789]\d{2}|624)\s?\d{3}\s?\d{3})$/);
534 }, "Please specify a valid mobile number");
535
536 /*
537  * The número de identidad de extranjero ( NIE )is a code used to identify the non-nationals in Spain
538  */
539 $.validator.addMethod( "nieES", function( value ) {
540         "use strict";
541
542         value = value.toUpperCase();
543
544         // Basic format test
545         if ( !value.match( "((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)" ) ) {
546                 return false;
547         }
548
549         // Test NIE
550         //T
551         if ( /^[T]{1}/.test( value ) ) {
552                 return ( value[ 8 ] === /^[T]{1}[A-Z0-9]{8}$/.test( value ) );
553         }
554
555         //XYZ
556         if ( /^[XYZ]{1}/.test( value ) ) {
557                 return (
558                         value[ 8 ] === "TRWAGMYFPDXBNJZSQVHLCKE".charAt(
559                                 value.replace( "X", "0" )
560                                         .replace( "Y", "1" )
561                                         .replace( "Z", "2" )
562                                         .substring( 0, 8 ) % 23
563                         )
564                 );
565         }
566
567         return false;
568
569 }, "Please specify a valid NIE number." );
570
571 /*
572  * The Número de Identificación Fiscal ( NIF ) is the way tax identification used in Spain for individuals
573  */
574 $.validator.addMethod( "nifES", function( value ) {
575         "use strict";
576
577         value = value.toUpperCase();
578
579         // Basic format test
580         if ( !value.match("((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)") ) {
581                 return false;
582         }
583
584         // Test NIF
585         if ( /^[0-9]{8}[A-Z]{1}$/.test( value ) ) {
586                 return ( "TRWAGMYFPDXBNJZSQVHLCKE".charAt( value.substring( 8, 0 ) % 23 ) === value.charAt( 8 ) );
587         }
588         // Test specials NIF (starts with K, L or M)
589         if ( /^[KLM]{1}/.test( value ) ) {
590                 return ( value[ 8 ] === String.fromCharCode( 64 ) );
591         }
592
593         return false;
594
595 }, "Please specify a valid NIF number." );
596
597 $.validator.addMethod("nowhitespace", function(value, element) {
598         return this.optional(element) || /^\S+$/i.test(value);
599 }, "No white space please");
600
601 /**
602 * Return true if the field value matches the given format RegExp
603 *
604 * @example $.validator.methods.pattern("AR1004",element,/^AR\d{4}$/)
605 * @result true
606 *
607 * @example $.validator.methods.pattern("BR1004",element,/^AR\d{4}$/)
608 * @result false
609 *
610 * @name $.validator.methods.pattern
611 * @type Boolean
612 * @cat Plugins/Validate/Methods
613 */
614 $.validator.addMethod("pattern", function(value, element, param) {
615         if (this.optional(element)) {
616                 return true;
617         }
618         if (typeof param === "string") {
619                 param = new RegExp(param);
620         }
621         return param.test(value);
622 }, "Invalid format.");
623
624 /**
625  * Dutch phone numbers have 10 digits (or 11 and start with +31).
626  */
627 $.validator.addMethod("phoneNL", function(value, element) {
628         return this.optional(element) || /^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9]){8}$/.test(value);
629 }, "Please specify a valid phone number.");
630
631 /* For UK phone functions, do the following server side processing:
632  * Compare original input with this RegEx pattern:
633  * ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$
634  * Extract $1 and set $prefix to '+44<space>' if $1 is '44', otherwise set $prefix to '0'
635  * Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2.
636  * A number of very detailed GB telephone number RegEx patterns can also be found at:
637  * http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers
638  */
639 $.validator.addMethod("phoneUK", function(phone_number, element) {
640         phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
641         return this.optional(element) || phone_number.length > 9 &&
642                 phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?)|(?:\(?0))(?:\d{2}\)?\s?\d{4}\s?\d{4}|\d{3}\)?\s?\d{3}\s?\d{3,4}|\d{4}\)?\s?(?:\d{5}|\d{3}\s?\d{3})|\d{5}\)?\s?\d{4,5})$/);
643 }, "Please specify a valid phone number");
644
645 /**
646  * matches US phone number format
647  *
648  * where the area code may not start with 1 and the prefix may not start with 1
649  * allows '-' or ' ' as a separator and allows parens around area code
650  * some people may want to put a '1' in front of their number
651  *
652  * 1(212)-999-2345 or
653  * 212 999 2344 or
654  * 212-999-0983
655  *
656  * but not
657  * 111-123-5434
658  * and not
659  * 212 123 4567
660  */
661 $.validator.addMethod("phoneUS", function(phone_number, element) {
662         phone_number = phone_number.replace(/\s+/g, "");
663         return this.optional(element) || phone_number.length > 9 &&
664                 phone_number.match(/^(\+?1-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
665 }, "Please specify a valid phone number");
666
667 /* For UK phone functions, do the following server side processing:
668  * Compare original input with this RegEx pattern:
669  * ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$
670  * Extract $1 and set $prefix to '+44<space>' if $1 is '44', otherwise set $prefix to '0'
671  * Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2.
672  * A number of very detailed GB telephone number RegEx patterns can also be found at:
673  * http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers
674  */
675 //Matches UK landline + mobile, accepting only 01-3 for landline or 07 for mobile to exclude many premium numbers
676 $.validator.addMethod("phonesUK", function(phone_number, element) {
677         phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
678         return this.optional(element) || phone_number.length > 9 &&
679                 phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?|0)(?:1\d{8,9}|[23]\d{9}|7(?:[1345789]\d{8}|624\d{6})))$/);
680 }, "Please specify a valid uk phone number");
681
682 /**
683  * Matches a valid Canadian Postal Code
684  *
685  * @example jQuery.validator.methods.postalCodeCA( "H0H 0H0", element )
686  * @result true
687  *
688  * @example jQuery.validator.methods.postalCodeCA( "H0H0H0", element )
689  * @result false
690  *
691  * @name jQuery.validator.methods.postalCodeCA
692  * @type Boolean
693  * @cat Plugins/Validate/Methods
694  */
695 $.validator.addMethod( "postalCodeCA", function( value, element ) {
696         return this.optional( element ) || /^[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d$/.test( value );
697 }, "Please specify a valid postal code" );
698
699 /* Matches Italian postcode (CAP) */
700 $.validator.addMethod("postalcodeIT", function(value, element) {
701         return this.optional(element) || /^\d{5}$/.test(value);
702 }, "Please specify a valid postal code");
703
704 $.validator.addMethod("postalcodeNL", function(value, element) {
705         return this.optional(element) || /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test(value);
706 }, "Please specify a valid postal code");
707
708 // Matches UK postcode. Does not match to UK Channel Islands that have their own postcodes (non standard UK)
709 $.validator.addMethod("postcodeUK", function(value, element) {
710         return this.optional(element) || /^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))\s?([0-9][ABD-HJLNP-UW-Z]{2})|(GIR)\s?(0AA))$/i.test(value);
711 }, "Please specify a valid UK postcode");
712
713 /*
714  * Lets you say "at least X inputs that match selector Y must be filled."
715  *
716  * The end result is that neither of these inputs:
717  *
718  *      <input class="productinfo" name="partnumber">
719  *      <input class="productinfo" name="description">
720  *
721  *      ...will validate unless at least one of them is filled.
722  *
723  * partnumber:  {require_from_group: [1,".productinfo"]},
724  * description: {require_from_group: [1,".productinfo"]}
725  *
726  * options[0]: number of fields that must be filled in the group
727  * options[1]: CSS selector that defines the group of conditionally required fields
728  */
729 $.validator.addMethod("require_from_group", function(value, element, options) {
730         var $fields = $(options[1], element.form),
731                 $fieldsFirst = $fields.eq(0),
732                 validator = $fieldsFirst.data("valid_req_grp") ? $fieldsFirst.data("valid_req_grp") : $.extend({}, this),
733                 isValid = $fields.filter(function() {
734                         return validator.elementValue(this);
735                 }).length >= options[0];
736
737         // Store the cloned validator for future validation
738         $fieldsFirst.data("valid_req_grp", validator);
739
740         // If element isn't being validated, run each require_from_group field's validation rules
741         if (!$(element).data("being_validated")) {
742                 $fields.data("being_validated", true);
743                 $fields.each(function() {
744                         validator.element(this);
745                 });
746                 $fields.data("being_validated", false);
747         }
748         return isValid;
749 }, $.validator.format("Please fill at least {0} of these fields."));
750
751 /*
752  * Lets you say "either at least X inputs that match selector Y must be filled,
753  * OR they must all be skipped (left blank)."
754  *
755  * The end result, is that none of these inputs:
756  *
757  *      <input class="productinfo" name="partnumber">
758  *      <input class="productinfo" name="description">
759  *      <input class="productinfo" name="color">
760  *
761  *      ...will validate unless either at least two of them are filled,
762  *      OR none of them are.
763  *
764  * partnumber:  {skip_or_fill_minimum: [2,".productinfo"]},
765  * description: {skip_or_fill_minimum: [2,".productinfo"]},
766  * color:               {skip_or_fill_minimum: [2,".productinfo"]}
767  *
768  * options[0]: number of fields that must be filled in the group
769  * options[1]: CSS selector that defines the group of conditionally required fields
770  *
771  */
772 $.validator.addMethod("skip_or_fill_minimum", function(value, element, options) {
773         var $fields = $(options[1], element.form),
774                 $fieldsFirst = $fields.eq(0),
775                 validator = $fieldsFirst.data("valid_skip") ? $fieldsFirst.data("valid_skip") : $.extend({}, this),
776                 numberFilled = $fields.filter(function() {
777                         return validator.elementValue(this);
778                 }).length,
779                 isValid = numberFilled === 0 || numberFilled >= options[0];
780
781         // Store the cloned validator for future validation
782         $fieldsFirst.data("valid_skip", validator);
783
784         // If element isn't being validated, run each skip_or_fill_minimum field's validation rules
785         if (!$(element).data("being_validated")) {
786                 $fields.data("being_validated", true);
787                 $fields.each(function() {
788                         validator.element(this);
789                 });
790                 $fields.data("being_validated", false);
791         }
792         return isValid;
793 }, $.validator.format("Please either skip these fields or fill at least {0} of them."));
794
795 /* Validates US States and/or Territories by @jdforsythe
796  * Can be case insensitive or require capitalization - default is case insensitive
797  * Can include US Territories or not - default does not
798  * Can include US Military postal abbreviations (AA, AE, AP) - default does not
799  *
800  * Note: "States" always includes DC (District of Colombia)
801  *
802  * Usage examples:
803  *
804  *  This is the default - case insensitive, no territories, no military zones
805  *  stateInput: {
806  *     caseSensitive: false,
807  *     includeTerritories: false,
808  *     includeMilitary: false
809  *  }
810  *
811  *  Only allow capital letters, no territories, no military zones
812  *  stateInput: {
813  *     caseSensitive: false
814  *  }
815  *
816  *  Case insensitive, include territories but not military zones
817  *  stateInput: {
818  *     includeTerritories: true
819  *  }
820  *
821  *  Only allow capital letters, include territories and military zones
822  *  stateInput: {
823  *     caseSensitive: true,
824  *     includeTerritories: true,
825  *     includeMilitary: true
826  *  }
827  *
828  *
829  *
830  */
831
832 jQuery.validator.addMethod("stateUS", function(value, element, options) {
833         var isDefault = typeof options === "undefined",
834                 caseSensitive = ( isDefault || typeof options.caseSensitive === "undefined" ) ? false : options.caseSensitive,
835                 includeTerritories = ( isDefault || typeof options.includeTerritories === "undefined" ) ? false : options.includeTerritories,
836                 includeMilitary = ( isDefault || typeof options.includeMilitary === "undefined" ) ? false : options.includeMilitary,
837                 regex;
838
839         if (!includeTerritories && !includeMilitary) {
840                 regex = "^(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$";
841         } else if (includeTerritories && includeMilitary) {
842                 regex = "^(A[AEKLPRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$";
843         } else if (includeTerritories) {
844                 regex = "^(A[KLRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$";
845         } else {
846                 regex = "^(A[AEKLPRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$";
847         }
848
849         regex = caseSensitive ? new RegExp(regex) : new RegExp(regex, "i");
850         return this.optional(element) || regex.test(value);
851 },
852 "Please specify a valid state");
853
854 // TODO check if value starts with <, otherwise don't try stripping anything
855 $.validator.addMethod("strippedminlength", function(value, element, param) {
856         return $(value).text().length >= param;
857 }, $.validator.format("Please enter at least {0} characters"));
858
859 $.validator.addMethod("time", function(value, element) {
860         return this.optional(element) || /^([01]\d|2[0-3])(:[0-5]\d){1,2}$/.test(value);
861 }, "Please enter a valid time, between 00:00 and 23:59");
862
863 $.validator.addMethod("time12h", function(value, element) {
864         return this.optional(element) || /^((0?[1-9]|1[012])(:[0-5]\d){1,2}(\ ?[AP]M))$/i.test(value);
865 }, "Please enter a valid time in 12-hour am/pm format");
866
867 // same as url, but TLD is optional
868 $.validator.addMethod("url2", function(value, element) {
869         return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
870 }, $.validator.messages.url);
871
872 /**
873  * Return true, if the value is a valid vehicle identification number (VIN).
874  *
875  * Works with all kind of text inputs.
876  *
877  * @example <input type="text" size="20" name="VehicleID" class="{required:true,vinUS:true}" />
878  * @desc Declares a required input element whose value must be a valid vehicle identification number.
879  *
880  * @name $.validator.methods.vinUS
881  * @type Boolean
882  * @cat Plugins/Validate/Methods
883  */
884 $.validator.addMethod("vinUS", function(v) {
885         if (v.length !== 17) {
886                 return false;
887         }
888
889         var LL = [ "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ],
890                 VL = [ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 7, 9, 2, 3, 4, 5, 6, 7, 8, 9 ],
891                 FL = [ 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ],
892                 rs = 0,
893                 i, n, d, f, cd, cdv;
894
895         for (i = 0; i < 17; i++) {
896                 f = FL[i];
897                 d = v.slice(i, i + 1);
898                 if (i === 8) {
899                         cdv = d;
900                 }
901                 if (!isNaN(d)) {
902                         d *= f;
903                 } else {
904                         for (n = 0; n < LL.length; n++) {
905                                 if (d.toUpperCase() === LL[n]) {
906                                         d = VL[n];
907                                         d *= f;
908                                         if (isNaN(cdv) && n === 8) {
909                                                 cdv = LL[n];
910                                         }
911                                         break;
912                                 }
913                         }
914                 }
915                 rs += d;
916         }
917         cd = rs % 11;
918         if (cd === 10) {
919                 cd = "X";
920         }
921         if (cd === cdv) {
922                 return true;
923         }
924         return false;
925 }, "The specified vehicle identification number (VIN) is invalid.");
926
927 $.validator.addMethod("zipcodeUS", function(value, element) {
928         return this.optional(element) || /^\d{5}(-\d{4})?$/.test(value);
929 }, "The specified US ZIP Code is invalid");
930
931 $.validator.addMethod("ziprange", function(value, element) {
932         return this.optional(element) || /^90[2-5]\d\{2\}-\d{4}$/.test(value);
933 }, "Your ZIP-code must be in the range 902xx-xxxx to 905xx-xxxx");
934
935 }));