Skip to content

Instantly share code, notes, and snippets.

@electricjesus
Created August 13, 2014 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electricjesus/1383ebac8106c466fb8c to your computer and use it in GitHub Desktop.
Save electricjesus/1383ebac8106c466fb8c to your computer and use it in GitHub Desktop.
getCreditCardType
// automatic creditcard detection @Seth Malaki `Electric Jesus` (c) 2012
// returns credit type on success. returns null if either unsupported or fails checksum validation (Luhn algorithm).
function getCreditCardType(accountNumber, doVerify)
{
var typeKey = null;
// inspect account number, no dashes
var creditCardInspectors = {
VI : /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/, // Visa
MC : /^5[1-5][0-9]{14}$/, // Mastercard
AE : /^3[47][0-9]{13}$/, // Amex
DI : /^6(?:011|5[0-9]{2})[0-9]{12}$/, // Discover
DC : /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/, // Diner's Club
JC : /^(?:2131|1800|35\d{3})\d{11}$/ // JCB
};
jQuery.each(creditCardInspectors, function(key, value) {
//console.log(key);
//console.log(value.test(accountNumber));
if(value.test(accountNumber) == true) {
if(doVerify != true) {
typeKey = key; return;
}
else { // Luhn algorithm
var checksum = 0;
for (var i=(2-(accountNumber.length % 2)); i<=accountNumber.length; i+=2) {
checksum += parseInt(accountNumber.charAt(i-1));
}
for (var i=(accountNumber.length % 2) + 1; i<accountNumber.length; i+=2) {
var digit = parseInt(accountNumber.charAt(i-1)) * 2;
if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
}
if ((checksum % 10) == 0) { typeKey = key; return; } else { return null; }
}
}
});
//not found
return typeKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment