WebReference.com - Chapter 10 selections: Practical JavaScript for the Usable Web from glasshaus (1/5).
[next] |
Practical JavaScript for the Usable Web
Validating a Credit Card Number
[Editor's note: the example code discussed in this excerpt is targeted to version 4 or later Web browsers.]
Our final validation method checks whether a credit card number could be a valid card number. Note that I say "could be" rather than "is"--just because the number is valid, doesn't mean that the card has been allocated or that it has not been canceled, if it was allocated. Only server-side processing can possibly validate a card number. However, what we can do here is check that the user hasn't made an accidental mistake so that we can get them to rectify any mistakes before we attempt server-side checks.
As we'll see shortly, validating a credit card is much more complex than any of the validation methods we have created so far. There are three checks we can perform client-side:Check that only numbers or spaces are given in the credit card number-not letters or other characters.
Check that, for the given card type, the number of digits given is valid and the prefix to the number is valid.
Use the Luhn formula to check the validity of the entered credit card number. This is a special algorithm that can be applied to most credit card numbers to check that the number would be valid.
We'll be using all three of these checks in our method (below, and see the Editor's note on page 5).
Validate.prototype.isValidCreditCardNumber = function(cardNumber, cardType)
{
var isValid = false;
var ccCheckRegExp = /[^\d ]/;
isValid = !ccCheckRegExp.test(cardNumber);
if (isValid)
{
var cardNumbersOnly = cardNumber.replace(/ /g,"");
var cardNumberLength = cardNumbersOnly.length;
var lengthIsValid = false;
var prefixIsValid = false;
var prefixRegExp;
switch(cardType)
{
case "mastercard":
lengthIsValid = (cardNumberLength == 16);
prefixRegExp = /^5[1-5]/;
break;
case "visa":
lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
prefixRegExp = /^4/;
break;
case "amex":
lengthIsValid = (cardNumberLength == 15);
prefixRegExp = /^3(4|7)/;
break;
default:
prefixRegExp = /^$/;
alert("Card type not found");
}
prefixIsValid = prefixRegExp.test(cardNumbersOnly);
isValid = prefixIsValid && lengthIsValid;
}
if (isValid)
{
var numberProduct;
var numberProductDigitIndex;
var checkSumTotal = 0;
for (digitCounter = cardNumberLength - 1;
digitCounter >= 0;
digitCounter--)
{
checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
digitCounter--;
numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
for (var productDigitCounter = 0;
productDigitCounter < numberProduct.length;
productDigitCounter++)
{
checkSumTotal +=
parseInt(numberProduct.charAt(productDigitCounter));
}
}
isValid = (checkSumTotal % 10 == 0);
}
return isValid;
}
[next] |
Created: April 15, 2002
Revised: April 19, 2002
URL: https://webreference.com/programming/javascript/practical/chap10/