View Single Post
Old 12-05-2010, 09:00 AM   PM User | #7
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,032
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Code:
<form name = "myForm">
<p> Enter credit card number <input type = "text" name = "CCNumber" maxlength = "16" onblur = "luhnCheck(this)"></p>
</form>

<script type = "text/javascript">

function luhnCheck(cardNum)  {

var failflag = 0;
cardNum = cardNum.value;
cardNum = cardNum.replace(/[^\d]/g, "");  // strip non-digits
if (cardNum.length <15 || cardNum.length > 16) {failflag = 1}
var firstDigit = cardNum.substr(0,1);
if (firstDigit < 3 || firstDigit > 6) {failflag = 1}

if (firstDigit == 3) {
if (!/^3[47][0-9]{13}$/.test(cardNum)) {
alert ("American Express numbers must be 15 digits starting with 34 or 37");  // test example 378282246310005
}
}
if (firstDigit == 4) {
if (!/^4[0-9]{12}(?:[0-9]{3})?$/.test(cardNum)) {
alert ("Visa numbers must be 16 digits starting with 4");  // test example 4111111111111111
}
}
if (firstDigit == 5) {
if (!/^5[1-5][0-9]{14}$/.test(cardNum)) {
alert ("MasterCard numbers must be 16 digits starting with 51 - 55");  // test example 5105105105105100
}
}

var ccArray = cardNum.split("");
ccArray = ccArray.reverse();

var digitString = "";
var digitSum = 0;
for (var counter = 0; counter < ccArray.length; counter++ )	{
var current_digit = parseInt( ccArray[counter] );
if (counter %2 != 0) {
ccArray	[counter] *= 2;
}
digitString += ccArray[counter];
}

for (counter = 0; counter < digitString.length; counter ++) {
current_digit = parseInt(digitString.charAt(counter));
digitSum += current_digit
}
if (digitSum % 10 != 0 ) {failflag = 1}

if (failflag == 0) {
alert ("The card number is valid \(passes Luhn algorithm\)  ")
return true
}
else {
alert ("The card number is INVALID - please re-enter it ");
document.myForm.CCNumber.value = "";
document.myForm.CCNumber.focus();
return false
}

}

</script>
You can easily check the card brand using firstDigit to determine.


Quizmaster: What season is said to start on the longest day in December?
Contestant: Spring.
Quizmaster: December, for God's sake!
Contestant: Summer.

Last edited by Philip M; 12-05-2010 at 09:38 AM..
Philip M is offline   Reply With Quote