JavaScript Credit Card Validation Function

This JavaScript function checks the validity of a credit card specified by the supplied parameters containing the card number and card type. Note that this routine does not supply credit card verification functionality, which can only be provided from within the server. It is, however, useful for intercepting user errors, and hence help provide a friendlier user-interface.

The specifications for valid credit cards have been taken from various sources on the web. The commonest credit cards are are supported in this implementation, but more may be added as required. One of the advantages of this routine is the ease with which additional cards may be added, as it is totally data driven.

Try the routine. Although no attempt is made to capture the input, it is suggested that you don't provide the number of your own credit card. The following are credit card numbers in a valid format:

American Express3400 0000 0000 009
Carte Blanche3000 0000 0000 04
Discover6011 0000 0000 0004
Diners Club3852 0000 0232 37
enRoute2014 0000 0000 009
JCB3530 111333300000
MasterCard5500 0000 0000 0004
Solo6334 0000 0000 0004
Switch4903 0100 0000 0009
Visa4111 1111 1111 1111
Laser6304 1000 0000 0008

Select credit card: Enter number:

The function returns true or false, depending on whether the credit card name / number combination is found to be valid. If it is not valid, a numeric code is loaded into a global variable, which may be used to index into a global array of error messages. In this example, the input fields have ids of CardType and CardNumber. The submit button has an onclick="testCreditCard();" associated with it. This latter function calls the main checkCreditCard function as follows:

function testCreditCard () {
  myCardNo = document.getElementById('CardNumber').value;
  myCardType = document.getElementById('CardType').value;
  if (checkCreditCard (myCardNo,myCardType)) {
    alert ("Credit card has a valid format")
  } 
  else {alert (ccErrors[ccErrorNo])};
}

The credit card details are held in an array within the function, and additional cards may be readily added. The format of the arrray is as follows:

cards [0] = {name: "Visa", 
             length: "13,16", 
             prefixes: "4",
             checkdigit: true};

Download compressed JavaScript file (2,746 bytes)

Note: This routine was last updated on 17th October 2012 to correct a Diners Club bug. Thanks to Pietro Cerri.