Last active
February 21, 2025 13:22
-
Star
(205)
You must be signed in to star a gist -
Fork
(49)
You must be signed in to fork a gist
-
-
Save DiegoSalazar/4075533 to your computer and use it in GitHub Desktop.
Luhn algorithm in Javascript. Check valid credit card numbers
This file contains 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
// Takes a credit card string 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. | |
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; | |
} |
Thank you! Nice work !
I'm Getting false result for Dankort (PBS) | 76009244561
Can someone answer for me on this ?
Thanks! Great Job!
I used this Credit Card Generator and it's showing almost accurate result.
they maintained maximum bank's bin code database. you must have to visit this site.
Hi buddy,
I pull your code in my local repository, I found issues with your code It validate all types of Credit cards (like Amex, Visa, Diners Club) most of the card number are found invalid.
After that I use credit card validator on CardGenerators.com that gives me perfect result. It also validate 15, 16 and 19 digit credit cards.
The code can be rewritten as:
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.
let nCheck = 0;
value = value.replace(/\D/g, "");
for (let n = 0; n < value.length; n++) {
let nDigit = parseInt(value[n], 10);
if (!((n + value.length) % 2) && (nDigit *= 2) > 9) nDigit -= 9;
nCheck += nDigit;
}
return (nCheck % 10) === 0;
}
Or even cleaner
export const luhn = (value) => {
let nCheck = 0;
if (value && /[0-9-\s]+/.test(value)) {
value = value.replace(/\D/g, '');
value.split('').forEach((v, n) => {
let nDigit = parseInt(v, 10);
if (!((value.length + n) % 2) && (nDigit *= 2) > 9) {
nDigit -= 9;
}
nCheck += nDigit;
});
}
return (nCheck % 10) === 0;
};
A shitty one-liner:
const luhn = numbers => numbers.split('').map((value, index) => index % 2 === 0 ? Number(value) * 2 <= 9 ? Number(value) * 2 : Number(Number(`${Number(value) * 2}`.split('')[0]) + Number(`${Number(value) * 2}`.split('')[1])) : Number(value)).reduce((a, b) => a + b).toString().split('')[1] === '0';
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working well, thank you very much Diego!