Create a gist now

Instantly share code, notes, and snippets.

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;
}
@mnadee123

Nicely worked.

@JonDum
JonDum commented Feb 12, 2014

Tested with all the test card numbers from http://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm

Worked with all. Good job!

@Maxhodges

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

@Brilliand

@Maxhodges - To generate a check digit, set bEven to true initially, and return (1000 - nCheck) % 10.

@MohamedAlaa

Execution time is very high: 35128.324ms

I've tried another Algorithm and it reported 0.059ms https://gist.github.com/ShirtlessKirk/2134376

@manishatGit

Quite helpful !!

@javierverb

Thanks!!! great work! 😄

@kendepelchin

Great!

@mscheffer

@mohamed execution time can't be 35 seconds !!

@chetankmayank

hi..can i get the code for aadhar card number validation using javascript and c#

@tkMageztik

awesome, thank you so much.

@fullstacked

This is not working with Amex cards. Can anyone pls guide me. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment