Skip to content

Instantly share code, notes, and snippets.

@vinothbabu
Last active December 17, 2015 00:39
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 vinothbabu/5522189 to your computer and use it in GitHub Desktop.
Save vinothbabu/5522189 to your computer and use it in GitHub Desktop.
Luhn algorithm - JavaScript implementation
function CreditCardValidator() {
}
CreditCardValidator.prototype = {
isValid: function (identifier) {
var num,
sum = 0,
alt;
var myRegxp = /^([0-9]){13,19}$/;
if (myRegxp.test(identifier.length)) {
return false;
}
var i = identifier.length - 1;
while (i >= 0) {
num = parseInt(identifier.charAt(i), 10);
if (isNaN(num)) {
return false;
}
if (alt) {
document.write(num);
num = num * 2;
if (num > 9) {
num = num - 9;
}
}
alt = !alt;
sum = sum + num;
i--;
}
return (sum % 10 == 0);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script type="text/javascript" src="CreditCardValidator.js"></script>
</head>
<body>
<script TYPE="text/javascript">
var valid = new CreditCardValidator();
alert(valid.isValid("0123765443210190"));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment