forked from Cimpress-MCP/postal-codes-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostal-codes.js
More file actions
82 lines (65 loc) · 2.23 KB
/
postal-codes.js
File metadata and controls
82 lines (65 loc) · 2.23 KB
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
var path = require('path');
var byAlpha2 = require(path.join(__dirname, 'generated', 'postal-codes-alpha2.json'));
var byAlpha3 = require(path.join(__dirname, 'generated', 'postal-codes-alpha3.json'));
module.exports.validate = function (countryCode, postalCode, callback) {
if (callback) {
return validatePostalCodeInternal(countryCode, postalCode, callback);
}
var result;
validatePostalCodeInternal(countryCode, postalCode, function (err, isValid) {
result = isValid;
});
return result;
};
function validatePostalCodeInternal(countryCode, postalCode, callback) {
if (!countryCode) {
callback('Invalid country code.');
return;
}
if (!postalCode) {
callback('Invalid postal code.');
return;
}
var countryData = undefined;
countryCode = countryCode.trim();
// Is it alpha2 ?
if (countryCode.length == 2) {
countryData = byAlpha2[countryCode.toUpperCase()];
}
// Is it alpha3 ?
if (countryCode.length == 3) {
countryData = byAlpha3[countryCode.toUpperCase()];
}
if (!countryData) {
callback('Unknown alpha2/alpha3 country code: ' + countryCode);
return;
}
var format = require(path.join(__dirname, 'formats', countryData.postalCodeFormat));
if (!format) {
callback('Failed to load postal code format "' + countryData.postalCodeFormat + '".');
return;
}
postalCode = postalCode.toString().trim();
var preparedPostalCode = postalCode.slice(0);
for(var i=0; i<format.RedundantCharacters.length; i++) {
preparedPostalCode = preparedPostalCode.replace(new RegExp(format.RedundantCharacters[i], 'g'), '');
}
var expression = format.ValidationRegex;
if (expression instanceof Array) {
expression = '^' + expression.join('|') + '$';
}
var regexp = new RegExp(expression, 'i');
var result = regexp.exec(preparedPostalCode);
if (!result) {
// Invalid postal code
callback(null, false);
return;
}
if (result[0].toLowerCase() != preparedPostalCode.toLowerCase()) {
// Found "sub" match
callback(null, false);
return;
}
// Valid postal code
callback(null, true);
}