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 dependent.
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 Express | 3400 0000 0000 009 |
| Carte Blanche | 3000 0000 0000 04 |
| Discover | 6011 0000 0000 0004 |
| Diner's Club | 3000 0000 0000 04 |
| enRoute | 2014 0000 0000 009 |
| JCB | 2131 0000 0000 0008 |
| MasterCard | 5500 0000 0000 0004 |
| Solo | 6334 0000 0000 0004 |
| Switch | 4903 0100 0000 0009 |
| Visa | 4111 1111 1111 1111 |
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.43 KB)
Note: This routine was updated on the 18th January 2008 to add support for 18 digit Maestro cards. Thanks to David Groom of Vectis Webdesign for pointing out the error.