WebReference.com - Chapter 10 selections: Practical JavaScript for the Usable Web from glasshaus (5/5). | WebReference

# WebReference.com - Chapter 10 selections: Practical JavaScript for the Usable Web from glasshaus (5/5).

 [previous]

### Practical JavaScript for the Usable Web

In the table below, we show what digits are extracted and what values added to the running total for the example card number `4221 3456 1243 1287`.

Once we have our result, in the table above that's `65`, we then find its modulus 10 value, that is the remainder left over when the running total is divided by ten. If it's zero, we have ourselves a valid credit card number, otherwise it's a fake. We set `isValid` to the result of the Boolean expression comparing the remainder to zero-Âif true it's valid, if false it's invalid. In our example, we have `65`, the modulus 10 value of which is `5`, so the example number is invalid-Âyou didn't really think I'd give my credit card number out now did you?

[Editor's note--UPDATE, 4/19/02: As originally published (both here and in the actual book) the function described in this excerpt was flawed, in that it did not add the last (left-most) digit of the credit card number into the checksum for card numbers with an odd number of digits (i.e., AmEx, Visa with 13 digits). As originally published, the outer loop in the script read:

``````     for (digitCounter = cardNumberLength - 1;
digitCounter > 0;
digitCounter--)
{``````

2 credit card digits were processed with each pass of the outer loop. On a 15 digit card, the loop begins with 14 (the last index digit in a 15 number card), then 12 on the next pass, then 10, 8, 6, 4, and 2. The final pass of the loop that would then add in the first digit of the card (at index position 0) never occurs; since the for loop is specifically tested for `digitCounter > 0`.

Of course, multiple fixes are possible. The publisher suggests altering the loop to check for `digitCounter >= 0`, which is what is now included in this article. However, as this can result in `NaN` problems with some platforms (we encountered errors when testing in Opera 6 and in early versions of NS4.x) when attempting to multiply an empty string by a number, we suggest the following minimal correction:

``````     for (digitCounter = cardNumberLength - 1;
digitCounter >= 0;
digitCounter--)
{
checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
if (digitCounter > 0)
}
digitCounter--;
numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
for (var productDigitCounter = 0;
productDigitCounter < numberProduct.length;
productDigitCounter++)
{
checkSumTotal +=
parseInt(numberProduct.charAt(productDigitCounter));
}
}
}``````

Our thanks to Jez Brett for being the first to point out the error.]

 [previous]

Created: April 15, 2002
Revised: April 19, 2002

URL: http://webreference.com/programming/javascript/practical/chap10/5.html