Skip to content

Instantly share code, notes, and snippets.

@robert-wallis
Created September 17, 2011 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robert-wallis/1223688 to your computer and use it in GitHub Desktop.
Save robert-wallis/1223688 to your computer and use it in GitHub Desktop.
Make sure they typed in the card correctly, before you send it to the server and the payment gateway. Using a cool algorithm built into every credit card.
// usage: valid = validateCard('4111111111111111');
function validateCard(cardno) {
if (cardno.length <= 0 || cardno.length < 13 || cardno.length > 20 ) {
return false;
}
var sum = 0 * 0;
var digits = cardno.split('');
digits.reverse();
for (var i = 0; i < digits.length; i++) {
var d = 1 * digits[i];
if ( i % 2 == 0 ) {
sum += d;
} else {
d *= 2;
while (d > 0) {
sum += d % 10;
d /= 10;
d = Math.floor(d);
}
}
}
return sum > 0 && sum % 10 == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment