Skip to content

Instantly share code, notes, and snippets.

@petercowan
Created November 18, 2011 03:17
Show Gist options
  • Save petercowan/1375495 to your computer and use it in GitHub Desktop.
Save petercowan/1375495 to your computer and use it in GitHub Desktop.
luhn check for jQuery-Validation-Engine
_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;
}
@mratzloff
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment