Main Page

Validating credit cards

function is then called like this:
alert(isValidDate(“5/5/2004”)); //outputs “true”
alert(isValidDate(“10/12/2009”)); //outputs “true”
alert(isValidDate(“6/13/2000”)); //outputs “false”
Validating credit cards
If you own or operate an e-commerce site, chances are you need to deal with credit card validation. Not
every incorrect credit card number is a fraudulent buyer; sometimes people just mistype or hit Enter too
early. To prevent a trip back to the server, you can create some basic patterns to determine if a given
credit card number is valid.
To start, consider a MasterCard credit card number, which must contain 16 digits. Of those 16 digits, the
first two digits must be a number between 51 and 55. A simple pattern is the following:
var reMasterCard = /^5[1-5]\d{14}$/;
Note the use of the caret and dollar sign to indicate the start and end of input to ensure that input
matches the entire string, not just part of it. This pattern is okay, but MasterCard numbers can be entered
either with spaces or dashes between every four digits, such as 5555-5555-5555-5555, which should also
be taken into account.
var reMasterCard = /^5[1-5]\d{2}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4}$/;
Actual credit card number validation requires using the Luhn algorithm. The Luhn algorithm is a
method to validate unique identifiers and is commonly used to validate credit card numbers. To run a
number through the algorithm, however, you must extract the numbers from the user input, which
means adding capturing groups:
var reMasterCard = /^(5[1-5]\d{2})[\s\-]?(\d{4})[\s\-]?(\d{4})[\s\-]?(\d{4})$/;
Now you can begin to build a function to validate a MasterCard number. The first step is to test a given
string against the pattern. If the string matches, then add the four digit groups back into a string (for
example, “5432-1234-5678-9012” should be converted to “5432123456789012”):
function isValidMasterCard(sText) {
var reMasterCard = /^(5[1-5]\d{2})[\s\-]?(\d{4})[\s\-]?(\d{4})[\s\-]?(\d{4})$/;
if (reMasterCard.test(sText)) {
var sCardNum = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
//Luhn algorithm here
} else {
return false;
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 218

JavaScript EditorFree JavaScript Editor     Ajax Editor