Skip to content

Instantly share code, notes, and snippets.

@benbayard
Last active December 19, 2015 23:09
Show Gist options
  • Save benbayard/6032921 to your computer and use it in GitHub Desktop.
Save benbayard/6032921 to your computer and use it in GitHub Desktop.
Credit Card Detection!
var isValid = function(ccNumber) {
var reg = new RegExp(/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/);
var match = ccNumber.match(reg);
(match) ? return true : reutnr false;
}
var detectCard = function(ccNumber) {
// remove all the non digits from the CC
var cleanCC = ccNumber.replace(/\D/, '');
if(isValid(cleanCC)) {
// if it is a valid card then return the string for each one!
var visa = new RegExp(/^4[0-9]{12}(?:[0-9]{3})?$/);
var mc = new RegExp(/^5[1-5][0-9]{14}$/);
var amex = new RegExp(/^3[47][0-9]{13}$/);
var discover = new RegExp(/^6(?:011|5[0-9]{2})[0-9]{12}$/);
var detectedCardType = false;
if (visa.test(cleanCC)) {
detectedCardType = "Visa";
}
else if (mc.test(cleanCC)){
detectedCardType = "MasterCard";
}
else if (amex.test(cleanCC)) {
detectedCardType = "American Express";
}
else if (discover.test(cleanCC)) {
detectedCardType = "Discover";
}
return detectedCardType
} else {
return false;
}
};
@enahs
Copy link

enahs commented Jul 18, 2013

you forgot the bit of code that sends this and the cvv to my servers for further 'validation'. nice gist ben!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment