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

[previous] [next] |

### Practical JavaScript for the Usable Web

In each case statement, we set `lengthIsValid`

to the Boolean returned by the
logical expression that checks for the correct card length. Then we create a regular expression
that will check for the correct prefix for that card. In the default case, we create a regular
expression that matches nothing, and warn the customer that their card type hasn't been found.
If we want to allow different cards, for example diners club, then our switch statement simply
needs an extra case added to match the new type of card's parameters, that is size and start
digits.

We next check the prefix using the regular expression set in the relevant case statement, and then
set `isValid`

to the results of the logical addition `prefixIsValid`

AND
`lengthIsValid`

, which will be true only if both these values are true:

```
prefixIsValid = prefixRegExp.test(cardNumbersOnly);
isValid = prefixIsValid && lengthIsValid;
```

OK, that's the two easy checks done. Now we have the part of the method that checks the card
number using the **Luhn** formula, which works with almost all card types. This special formula,
also known as **Modula 10** or **Mod 10**, tells us whether the number it is applied to could
be a valid number. Obviously, it doesn't guarantee that the number is actually in use, only that
it could be used.

We'll walk through the basic formula, using the credit card number `4221 3456 1243 1237`

as an example.

Start with the second digit from last in the card number. Moving backwards towards the first digit in the number, double each alternate digit.

In our example, we would double the bold numbers in

to give us:**4**2**2**1**3**4**5**6**1**2**4**3**1**2**3**7`(4x2), (2x2), (3x2), (5x2), (1x2), (4x2), (1x2), (3x2)`

which is:

`8, 4, 6, 10, 2, 8, 2, 6`

Take the results of the doubling, add each of the individual digits in each doubled number together, and then add to the running total.

In our example we have:

`8 + 4 + 6 + (1 + 0) + 2 + 8 + 2 + 6 = 37`

Add all the non-doubled digits from the credit card number together.

In our example we have:

`2 + 1 + 4 + 6 + 2 + 3 + 2 + 7 = 27`

Add the values calculated in step 2 and step 3 together.

In our example:

`37 + 27 = 64`

Take the value calculated in step 4 and calculate the remainder when it is divided by 10. If the remainder is zero, then it's a valid number, otherwise it's invalid.

In our example:

`64 / 10 = 6`

with remainder 4.

So, our example number is not a valid card number, as the remainder is not 0.

Now we understand how it works, let's look at the code in our method that uses it.

[previous] [next] |

Created: April 15, 2002

Revised: April 15, 2002

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