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