Last active
December 17, 2015 00:39
-
-
Save vinothbabu/5522189 to your computer and use it in GitHub Desktop.
Luhn algorithm - JavaScript implementation
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
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); | |
} | |
} |
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
<!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