Skip to content

Instantly share code, notes, and snippets.

@sheharyarn
Forked from DiegoSalazar/validate_credit_card.js
Created September 20, 2016 20:57
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 sheharyarn/c063f2841631ddc09e562a6407071f8a to your computer and use it in GitHub Desktop.
Save sheharyarn/c063f2841631ddc09e562a6407071f8a to your computer and use it in GitHub Desktop.
Luhn algorithm in Javascript. Check valid credit card numbers
// 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment