| 5048 |
dpurdie |
1 |
/**
|
|
|
2 |
* jQuery Form Validator Module: Security
|
|
|
3 |
* ------------------------------------------
|
|
|
4 |
* Created by Victor Jonsson <http://www.victorjonsson.se>
|
|
|
5 |
*
|
|
|
6 |
* This form validation module adds validators typically used on
|
|
|
7 |
* websites in the UK. This module adds the following validators:
|
|
|
8 |
* - ukvatnumber
|
|
|
9 |
*
|
|
|
10 |
* @website http://formvalidator.net/#uk-validators
|
|
|
11 |
* @license Dual licensed under the MIT or GPL Version 2 licenses
|
|
|
12 |
* @version 2.2.beta.69
|
|
|
13 |
*/
|
|
|
14 |
$.formUtils.addValidator({
|
|
|
15 |
name : 'ukvatnumber',
|
|
|
16 |
validatorFunction : function(number) {
|
|
|
17 |
|
|
|
18 |
// Code Adapted from http://www.codingforums.com/showthread.php?t=211967
|
|
|
19 |
// TODO: Extra Checking for other VAT Numbers (Other countries and UK Government/Health Authorities)
|
|
|
20 |
|
|
|
21 |
number = number.replace(/[^0-9]/g, '');
|
|
|
22 |
|
|
|
23 |
//Check Length
|
|
|
24 |
if(number.length < 9) {
|
|
|
25 |
return false;
|
|
|
26 |
}
|
|
|
27 |
|
|
|
28 |
var valid = false;
|
|
|
29 |
|
|
|
30 |
var VATsplit = [];
|
|
|
31 |
VATsplit = number.split("");
|
|
|
32 |
|
|
|
33 |
var checkDigits = Number(VATsplit[7] + VATsplit[8]); // two final digits as a number
|
|
|
34 |
|
|
|
35 |
var firstDigit = VATsplit[0];
|
|
|
36 |
var secondDigit = VATsplit[1];
|
|
|
37 |
if ((firstDigit == 0) && (secondDigit >0)) {
|
|
|
38 |
return false;
|
|
|
39 |
}
|
|
|
40 |
|
|
|
41 |
var total = 0;
|
|
|
42 |
for (var i=0; i<7; i++) { // first 7 digits
|
|
|
43 |
total += VATsplit[i]* (8-i); // sum weighted cumulative total
|
|
|
44 |
}
|
|
|
45 |
|
|
|
46 |
var c = 0;
|
|
|
47 |
var i = 0;
|
|
|
48 |
|
|
|
49 |
for (var m = 8; m>=2; m--) {
|
|
|
50 |
c += VATsplit[i]* m;
|
|
|
51 |
i++;
|
|
|
52 |
}
|
|
|
53 |
|
|
|
54 |
// Traditional Algorithm for VAT numbers issued before 2010
|
|
|
55 |
|
|
|
56 |
while (total > 0) {
|
|
|
57 |
total -= 97; // deduct 97 repeatedly until total is negative
|
|
|
58 |
}
|
|
|
59 |
total = Math.abs(total); // make positive
|
|
|
60 |
|
|
|
61 |
if (checkDigits == total) {
|
|
|
62 |
valid = true;
|
|
|
63 |
}
|
|
|
64 |
|
|
|
65 |
// If not valid try the new method (introduced November 2009) by subtracting 55 from the mod 97 check digit if we can - else add 42
|
|
|
66 |
|
|
|
67 |
if (!valid) {
|
|
|
68 |
total = total%97 // modulus 97
|
|
|
69 |
|
|
|
70 |
if (total >= 55) {
|
|
|
71 |
total = total - 55
|
|
|
72 |
} else {
|
|
|
73 |
total = total + 42
|
|
|
74 |
}
|
|
|
75 |
|
|
|
76 |
if (total == checkDigits) {
|
|
|
77 |
valid = true;
|
|
|
78 |
}
|
|
|
79 |
}
|
|
|
80 |
|
|
|
81 |
return valid;
|
|
|
82 |
},
|
|
|
83 |
errorMessage : '',
|
|
|
84 |
errorMessageKey: 'badUKVatAnswer'
|
|
|
85 |
});
|