Skip to content

Instantly share code, notes, and snippets.

@benjamincharity
Created July 31, 2015 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjamincharity/2ee418a3d6f1200c29ef to your computer and use it in GitHub Desktop.
Save benjamincharity/2ee418a3d6f1200c29ef to your computer and use it in GitHub Desktop.
Validate credit card with the luhn algorithm.
/*
* Check the validity of a credit card number
*
* https://gist.github.com/2134376
* Phil Green (ShirtlessKirk)
*
* @param {String} number
* @return {Bool} validity
*/
function luhnChk(number) {
var len = number.length;
var mul = 0;
var prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]];
var sum = 0;
while (len--) {
sum += prodArr[mul][parseInt(number.charAt(len), 10)];
mul ^= 1;
}
return sum % 10 === 0 && sum > 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment