Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active December 24, 2018 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yairEO/9c3b53bbfb00c0ff6c13 to your computer and use it in GitHub Desktop.
Save yairEO/9c3b53bbfb00c0ff6c13 to your computer and use it in GitHub Desktop.
MOD-10 validator in javascript
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');
@DaveSweeton
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment