Guest Post by Bill
In this tutorial, I will be describing a more effective way to validate credit cards when accepting payment on your site. This method provides smoother and more compact way of verification, eliminating the use of larger scripts. The plug-in I will be describing will help you so that you can check a credit card number you are given for correct checksum values as well as correct format before submitting for processing.
To begin, we will describe how this plug-in works. This plug-in takes details about a credit card and returns true or false depending whether the card passes checksum and date verification. It requires the following arguments:
Number: A Credit Card Number
Month: The Credit Card's Expiry Month
Year: The Credit Card's Expiry Year
Variables, Arrays, and Functions
left Local variable containing the first 4 digits of number
cclen Local variable containing the number of digits in number
chksum Local variable containing the card’s checksum
substr() Function to return a portion of a string
getTime() Function to get the current time and date
getFullYear() Function to get the year as a 4-digit number
getMonth() Function to get the month
This function first ensures that all three parameters passed to it are strings by adding the
empty string to them, like this:
number += ' '
month += ' '
year += ' '
Next, each argument is processed through a CleanupString() to ensure that they are in the formats required:
number = CleanupString(number, true, false, true, true)
month = CleanupString(month, true, false, true, true)
year = CleanupString(year, true, false, true, true)
After this, the variable left is assigned the first 4 digits of number, cclen is set to the
card number’s length, and chksum is initialized to 0:
var left = number.substr(0, 4)
var cclen = number.length
var chksum = 0
Now with several if() ... else if() statements we check that left contains a valid sequence that matches a known brand of credit card and, if it does, that the card number length in cclen is correct for the card type. However, If left doesn’t match a known card, or it matches one but cclen is the wrong length, then the plug-in returns false to indicate that the card cannot be verified.
If these initial tests are passed, the card’s checksum is then calculated using a very known algorithm that gives us just what we need (this algorithm was invented by a the famous IBM scientist Hans Peter Luhn)
for (var j = 1 - (cclen % 2) ; j < cclen ; j += 2)
if (j < cclen) chksum += number[j] * 1
for (j = cclen % 2 ; j < cclen ; j += 2)
{
if (j < cclen)
{
d = number[j] * 2
chksum += d < 10 ? d : d - 9
}
}
if (chksum % 10 != 0) return false
To use this plug-in, pass it a card number, expiry year, and month and it will return true or false. Of course, this algorithm tests only whether the card meets certain requirements. This program will give the customer a "heads up" to check their info before trying to submit their information; it does not test whether the user has entered a genuine card or whether the charge will go through. This plug-in is best for preventing errors before the processing state, e.g. catching mistakes made by customers in typing numbers, entering correct numbers in the wrong area of a form, etc).
Again, a big warning here: We are not connecting to a bank or any financial party to provide us any verification as to whether this card is good to go for a certain amount of payment or not.
The purpose of the plug-in is to catch typing errors, as well as people entering random data to see what happens.
Here is a full coded example using our previous code:
<h3>Your credit card details:</h3>
<font face='Courier New'>
Card Number: <input id='ccnum' type='text' name='n' size='24' /><br />
Expires: Month <input id='ccmonth' type='text' name='m' size='2' />
Year <input id='ccyear' type='text' name='y' size='4' /><br />
<button id='button'>Submit Credit Card</button>
<script>
window.onload = function()
{
O('button').onclick = function()
{
if (ValidateCreditCard(O('ccnum').value, O('ccmonth').value, O('ccyear').value))
alert("The card validated successfully")
else
alert("The card did not validate!")
}
}
</script>
If you are to use this plug-in with your own code, you will probably want to replace the onclick event attachment used in the example with a function attached to the onsubmit event of your form. Also, make sure that when you do this your function returns true if the card verifies to allow the form submission to complete, and false (along with and alert message stating the error message) if the card submission doesn’t validate, to stop the form submission from going through.
The full plug-in code:
CODE
function ValidateCreditCard(number, month, year)
{
number += ' '
month += ' '
year += ' '
number = CleanupString(number, true, false, true, true)
month = CleanupString(month, true, false, true, true)
year = CleanupString(year, true, false, true, true)
var left = number.substr(0, 4)
var cclen = number.length
var chksum = 0
if (left >= 3000 && left <= 3059 ||
left >= 3600 && left <= 3699 ||
left >= 3800 && left <= 3889)
{ // Diners Club
if (cclen != 14) return false
}
else if (left >= 3088 && left <= 3094 ||
left >= 3096 && left <= 3102 ||
left >= 3112 && left <= 3120 ||
left >= 3158 && left <= 3159 ||
left >= 3337 && left <= 3349 ||
left >= 3528 && left <= 3589)
{ // JCB
if (cclen != 16) return false
}
else if (left >= 3400 && left <= 3499 ||
left >= 3700 && left <= 3799)
{ // American Express
if (cclen != 15) return false
}
else if (left >= 3890 && left <= 3899)
{ // Carte Blanche
if (cclen != 14) return false
}
else if (left >= 4000 && left <= 4999)
{ // Visa
if (cclen != 13 && cclen != 16) return false
}
else if (left >= 5100 && left <= 5599)
{ // MasterCard
if (cclen != 16) return false
}
else if (left == 5610)
{ // Australian BankCard
if (cclen != 16) return false
}
else if (left == 6011)
{ // Discover
if (cclen != 16) return false
}
else return false // Unrecognized Card
for (var j = 1 - (cclen % 2) ; j < cclen ; j += 2)
if (j < cclen) chksum += number[j] * 1
for (j = cclen % 2 ; j < cclen ; j += 2)
{
if (j < cclen)
{
d = number[j] * 2
chksum += d < 10 ? d : d - 9
}
}
if (chksum % 10 != 0) return false
var date = new Date()
date.setTime(date.getTime())
if (year.length == 4) year = year.substr(2, 2)
if (year > 50)
return false
else if (year < (date.getFullYear() - 2000))
return false
else if ((date.getMonth() + 1) > month
return false
else
return true
}
CODE
So this is how we can use JavaScript in a more effective way to verify the credit card information.
About the Guest Author
This article was contributed by Bill at Spotted Frog Design, a web development and online marketing company based in the Philadelphia area. For more information about Spotted Frog, please visit their site, or follow them on Twitter at spottedfrog