Skip to content

Instantly share code, notes, and snippets.

@rajnandan1
Last active October 11, 2021 08:28
Show Gist options
  • Save rajnandan1/5768f4ed22f79f28a0da427a2be9760c to your computer and use it in GitHub Desktop.
Save rajnandan1/5768f4ed22f79f28a0da427a2be9760c to your computer and use it in GitHub Desktop.
check if a card number is valid
function valid_card(value) {
// Accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
// The Luhn Algorithm. It's so pretty.
let nCheck = 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 && (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