Main Page


if (reMasterCard.test(sText)) {
var sCardNum = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
return luhnCheckSum(sCardNum);
} else {
return false;
You can now pass in MasterCard numbers like this:
alert(isValidMasterCard(“5432 1234 5678 9012”)); //outputs “false”
alert(isValidMasterCard(“5432-1234-5678-9012”)); //outputs “false”
alert(isValidMasterCard(“5432123456789012”)); //outputs “false”
For other types of credit cards, you must know the rules governing their credit card numbers.
Visa card numbers can have either 13 or 16 digits and the first digit must always be 4, therefore, the pat-
tern to match a Visa number (with no spaces) is:
var reVisa = /^(4\d{12}(?:\d{3})?)$/;
A couple of things to note in this pattern:
A non-capturing group surrounds the final three digits of the card number because these three
digits alone aren’t of much use.
The question mark after the non-capturing group indicates that there should be either three
more digits or no more digits.
With the regular expression complete, you just extract the number and apply the Luhn algorithm:
function isValidVisa(sText) {
var reVisa = /^(4\d{12}(?:\d{3})?)$/;
if (reVisa.test(sText)) {
return luhnCheckSum(RegExp.$1);
} else {
return false;
For more on credit card number patterns and using Luhn’s algorithm, see
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 221

JavaScript EditorFree JavaScript Editor     Ajax Editor