JavaScript Luhn modulus implementation
The following luhn_check() function is a small JavaScript function which checks whether a number is a valid based on the Luhn algoritm. One common example of use is with credit and debit card numbers. This function may be used to check for valid credit card numbers, however additional checks may be desired, such as card prefix and length checks.
There’s a working example of this function to give you more of an idea of how it works!
/* Luhn algorithm number checker - (c) 2005-2009 - planzero.org * * This code has been released into the public domain, however please * * give credit to the original author where possible. */ function luhn_check(number) { //<![CDATA[ // Strip any non-digits (useful for credit card numbers with spaces and hyphens) var number=number.replace(/\D/g, ''); // Set the string length and parity var number_length=number.length; var parity=number_length % 2; // Loop through each digit and do the maths var total=0; for (i=0; i < number_length; i++) { var digit=number.charAt(i); // Multiply alternate digits by two if (i % 2 == parity) { digit=digit * 2; // If the sum is two digits, add them together (in effect) if (digit > 9) { digit=digit - 9; } } // Total up the digits total = total + parseInt(digit); } // If the total mod 10 equals 0, the number is valid if (total % 10 == 0) { return true; } else { return false; } //]]> }
you can replace:
// If the total mod 10 equals 0, the number is valid
if (total % 10 == 0) {
return true;
} else {
return false;
}
with
// If the total mod 10 equals 0, the number is valid
return (total % 10 == 0);
// If this is a “non-white-space characters” minimum contest, you can
// return instead:
return !(total % 10);
// or simply remove your ()’s… 18 vs 20 :-)
Hello, maybe this entry could be off topic but anyhow, Having been browsing around your website and it seems seriously cool. It is obvious that you know your topic and you seem passionate about it. We are creating a new web site and I am struggling to make it look great, and present the best quality writing. I have discovered a good deal from this internet site plus I anticipate further quality content and will be coming back soon. Many thanks.
Hi, possibly this post might be off topic but anyways, I have been browsing around your blog and it appears very neat. It is obvious that you know the topic and you seem passionate about it. We are constructing a fresh weblog plus I’m attempting to make it look good, as well as offer quality message. I have discovered much visiting your internet site and also I anticipate more quality information and will be coming back soon. Many thanks.