Last active
December 24, 2018 21:26
-
-
Save yairEO/9c3b53bbfb00c0ff6c13 to your computer and use it in GitHub Desktop.
MOD-10 validator in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var validateNum = function(num){ | |
num = num.replace(/-/g,''); | |
var calc, i, check, checksum = 0, r = [2,1]; // alternating routing table | |
// iterate on all the numbers in 'num' | |
for( i=num.length-1; i--; ){ | |
calc = num.charAt(i) * r[i % r.length]; | |
//console.log(num.charAt(i), r[i % r.length], [calc]); | |
// handle cases where it's a 2 digits number | |
calc = ((calc/10)|0) + (calc % 10); | |
checksum += calc; | |
} | |
check = (10-(checksum % 10)) % 10; // make sure to get '0' if checksum is '10' | |
checkDigit = num % 10; | |
return check == checkDigit; | |
} | |
validateNum('740428-0401'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning: this is not a proper MOD-10 implementation. It works with most cards, but fails with AMEX cards (likely because they are an odd number of digits). I switched to this implementation instead: https://gist.github.com/DiegoSalazar/4075533