Skip to content

Instantly share code, notes, and snippets.

@drewblas
Created January 28, 2014 19:31
Show Gist options
  • Save drewblas/8674471 to your computer and use it in GitHub Desktop.
Save drewblas/8674471 to your computer and use it in GitHub Desktop.
<html>
<head>
<script>
function check_cc() {
var r = document.getElementById("results");
var elem = document.getElementById("ccnum");
r.innerHTML = "Checking CC: " + elem.value + "<br>";
var result = valid_credit_card(elem.value);
r.innerHTML = r.innerHTML + "Valid? " + result + "<br>";
}
// takes the form field value and returns true on valid number
function valid_credit_card(value) {
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return "Invalid format";
// The Luhn Algorithm. It's so pretty.
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
</script>
</head>
<body>
<p>Enter your credit card number:</p>
<input id="ccnum" type="text"></input>
<button onclick="check_cc();">Check</button>
<h3>Results</h3>
<p id="results"></p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment