Skip to content

Instantly share code, notes, and snippets.

@oluies
Created August 1, 2012 11:49
Show Gist options
  • Save oluies/3226158 to your computer and use it in GitHub Desktop.
Save oluies/3226158 to your computer and use it in GitHub Desktop.
function luhn(cardnumber) {
// Build an array with the digits in the card number
var getdigits = /\d/g;
var digits = [];
while (match = getdigits.exec(cardnumber)) {
digits.push(parseInt(match[0], 10));
}
// Run the Luhn algorithm on the array
var sum = 0;
var alt = false;
for (var i = digits.length - 1; i >= 0; i--) {
if (alt) {
digits[i] *= 2;
if (digits[i] > 9) {
digits[i] -= 9;
}
}
sum += digits[i];
alt = !alt;
}
// Card number turns out to be invalid anyway
if (sum % 10 == 0) {
document.getElementById("notice").innerHTML += '; Luhn check passed';
} else {
document.getElementById("notice").innerHTML += '; Luhn check failed';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment