↑

Main Page

# statement

}

bIsOdd = !bIsOdd;

}

}

Adding the

else

statement to

if (bIsOdd)

accomplishes adding the odd position digits together. If the

number is greater than 9 (which means it has two digits), the number is transformed using a variety of

methods talked about earlier in the book:

1.

The number is transformed into a string using

toString()

.

2.

The string is then split into an array of two characters using

split()

. For example, 12 would be

split into an array of

“1”

and

“2”

.

3.

The array is combined with a plus sign using

join()

, so

“1”

and

“2”

become

“1+2”

.

4.

The resulting string is then passed in to

eval()

, which interprets it as literal code (so

“1+2”

is

added as 1+2 and returns 3).

The very last step is to add the two sums (from the even and odd position digits) and perform a modu-

lus (remainder) operation on the result. If the number is valid, the sum is equally divisible by 10 (so it

will be equal to 20, 30, 40, and so on).

function luhnCheckSum(sCardNum) {

var iOddSum = 0;

var iEvenSum = 0;

var bIsOdd = true;

for (var i=sCardNum.length-1; i >= 0; i--) {

var iNum = parseInt(sCardNum.charAt(i));

if (bIsOdd) {

iOddSum += iNum;

} else {

iNum = iNum * 2;

if (iNum > 9) {

iNum = eval(iNum.toString().split(“”).join(“+”));

}

iEvenSum += iNum;

}

bIsOdd = !bIsOdd;

}

return ((iEvenSum + iOddSum) % 10 == 0);

}

Add this method back into the

isValidMasterCard()

method, and you’re done:

function isValidMasterCard(sText) {

var reMasterCard = /^(5[1-5]\d{2})[\s\-]?(\d{4})[\s\-]?(\d{4})[\s\-]?(\d{4})$/;

220

Chapter 7

10_579088 ch07.qxd 3/28/05 11:38 AM Page 220

Free JavaScript Editor
Ajax Editor

©

↓