Created
November 18, 2011 03:17
-
-
Save petercowan/1375495 to your computer and use it in GitHub Desktop.
luhn check for jQuery-Validation-Engine
This file contains 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
_creditCard: function(field, rules, i, options) { | |
var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, ''); | |
var numDigits = cardNumber.length; | |
if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) { | |
var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String(); | |
do { | |
digit = parseInt(cardNumber.charAt(i)); | |
luhn += (pos++ % 2 == 0) ? digit * 2 : digit; | |
} while (--i >= 0) | |
for (i = 0; i < luhn.length; i++) { | |
sum += parseInt(luhn.charAt(i)); | |
} | |
valid = sum % 10 == 0; | |
} | |
if (!valid) return options.allrules.creditCard.alertText; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, Peter--this helped! I rewrote it slightly to be a bit more straightforward (removed the inline variable declarations, changed the do-while loop to a for loop, etc.). Also made it a normal function declaration so you can use as
class="validate[funcCall[validateCreditCard]]"
.https://gist.github.com/1724921