-
-
Save oluies/3226158 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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