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;
}
//]]>
}