-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathluhn.js
40 lines (34 loc) · 999 Bytes
/
luhn.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
"use strict";
/**
* Luhn algorithm checksum https://en.wikipedia.org/wiki/Luhn_algorithm
* Credit Card numbers, IMEI numbers, National Provider Identifier numbers and others
* @param value
* @param schema
* @return {boolean|{actual, expected, type}|ValidationError}
*
* Signature: function(value, field, parent, errors, context)
*/
module.exports = function({ schema, messages }, path, context) {
return {
source: `
if (typeof value !== "string") {
${this.makeError({ type: "string", actual: "value", messages })}
return value;
}
if (typeof value !== "string")
value = String(value);
val = value.replace(/\\D+/g, "");
var array = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
var len = val ? val.length : 0,
bit = 1,
sum = 0;
while (len--) {
sum += !(bit ^= 1) ? parseInt(val[len], 10) : array[val[len]];
}
if (!(sum % 10 === 0 && sum > 0)) {
${this.makeError({ type: "luhn", actual: "value", messages })}
}
return value;
`
};
};