forked from Cimpress-MCP/postal-codes-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (69 loc) · 2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const byAlpha2 = require("./generated/postal-codes-alpha2.json");
const byAlpha3 = require("./generated/postal-codes-alpha3.json");
let getFormat = require("./formats-web");
module.exports = {
validate: function(countryCode, postalCode) {
if (!countryCode) {
return "Missing country code.";
}
if (!postalCode) {
return "Missing postal code.";
}
let countryData = undefined;
let preparedCountryCode = countryCode.trim().toUpperCase();
// Is it alpha2 ?
if (preparedCountryCode.length == 2) {
countryData = byAlpha2[preparedCountryCode];
}
// Is it alpha3 ?
if (preparedCountryCode.length == 3) {
countryData = byAlpha3[preparedCountryCode];
}
if (!countryData) {
return "Unknown alpha2/alpha3 country code: " + preparedCountryCode;
}
let format = getFormat(countryData.postalCodeFormat);
if (!format) {
return (
'Failed to load postal code format "' +
countryData.postalCodeFormat +
'".'
);
}
let preparedPostalCode = postalCode
.toString()
.trim()
.slice(0);
for (let i = 0; i < format.RedundantCharacters.length; i++) {
preparedPostalCode = preparedPostalCode.replace(
new RegExp(format.RedundantCharacters[i], "g"),
""
);
}
let expression = format.ValidationRegex;
if (expression instanceof Array) {
expression = "^" + expression.join("|") + "$";
}
const regexp = new RegExp(expression, "i");
let result = regexp.exec(preparedPostalCode);
if (!result) {
// Invalid postal code
return (
"Postal code " +
preparedPostalCode +
" is not valid for country " +
preparedCountryCode
);
}
if (result[0].toLowerCase() != preparedPostalCode.toLowerCase()) {
// Found "sub" match
return (
"Postal code " +
preparedPostalCode +
" is not valid for country " +
preparedCountryCode
);
}
return true;
}
};