Skip to content

Instantly share code, notes, and snippets.

@cheeaun
Created July 20, 2009 19:22
Show Gist options
  • Save cheeaun/150619 to your computer and use it in GitHub Desktop.
Save cheeaun/150619 to your computer and use it in GitHub Desktop.
Luhn validation code in JavaScript (MooTools)
/*
* Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org
* Ported to Mootools by Chee Aun - http://cheeaun.com/
* http://planzero.org/code/bits/viewcode.php?src=luhn_check.js
* http://en.wikipedia.org/wiki/Luhn_algorithm
*/
String.implement({
isValidLuhn: function(){
var number = this.replace(/\D/g, ''); // strip non-digits
var len = number.length;
var parity = len % 2;
var total = 0;
for (i=0; i < len; i++) {
var digit = number.charAt(i);
// Multiply alternate digits by two
if (i % 2 == parity){
digit *= 2;
// If the sum is two digits, add them together (in effect)
if (digit > 9) digit -= 9;
}
// Total up the digits
total += parseInt(digit);
}
// If the total mod 10 equals 0, the number is valid
return (total % 10 == 0);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment