public
Last active

Luhn algorithm in Javascript. Check valid credit card numbers

  • Download Gist
validate_credit_card.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// takes the form field value and returns true on valid number
function valid_credit_card(value) {
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
 
// The Luhn Algorithm. It's so pretty.
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
 
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
 
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
 
nCheck += nDigit;
bEven = !bEven;
}
 
return (nCheck % 10) == 0;
}

anyone have the generate algorithm? I need to generate ID numbers with a check digit

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.