JavaScript to ID credit card type


I’m working on a subscription page which needs to identify the type of the entered credit card number, and display a logo accordingly. I came up with the following script to ID the card:


// get entered cc_number using jQuery
cc_number = $("#cc_number").val();


// remove spaces and hyphens
cc_number = cc_number.replace(/[ -]/g,"");


// initially the card type is unknown
cardtype = '';
$j("#cc_type").val("");


// define card names and their matching patterns
ccArray = {"visa" : "^4[0-9]{12}(?:[0-9]{3})?$",
"mastercard" : "^5[1-5][0-9]{14}$",
"discover" : "^6011[0-9]{12}$",
"amex" : "^3[47][0-9]{13}$"};


// identify the card type
for (key in ccArray) {
regex = new RegExp(ccArray[key]);
if (regex.test(cc_number)) {
cardtype = key;
break;
}
}

I validate the card number next (JS routine available elsewhere on the web), and if that's ok, display the logo using the card type.

  1. No comments yet.
(will not be published)