Created
July 20, 2009 19:22
-
-
Save cheeaun/150619 to your computer and use it in GitHub Desktop.
Luhn validation code in JavaScript (MooTools)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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