Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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;

Nicely worked.

JonDum commented Feb 12, 2014

Tested with all the test card numbers from

Worked with all. Good job!

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

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

Execution time is very high: 35128.324ms

I've tried another Algorithm and it reported 0.059ms

Quite helpful !!

Thanks!!! great work! 😄


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

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

awesome, thank you so much.

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

Nice work! Thanks!

Awesome work, thanks!

ayushya commented Apr 20, 2017

Code Works great.

Although nDigit variable declared on Line 7 is not being used[ and can be removed ] since its been redeclared inside the for loop.

Correct me if wrong @DiegoSalazar

I noticed one a little mistake in the end of the script;
If you type '0' or '00' or '0000000000' you will get true

My resolve to line 22:
return (nCheck !== 0) && (nCheck % 10) == 0

What do you think ?

ndigit is defined twice. jshint complains . line 12

Nice work, thank you!

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