Skip to content

Instantly share code, notes, and snippets.

@rajnandan1
Last active October 11, 2021 08:24
Show Gist options
  • Save rajnandan1/3c2c146466505f2fdeb82df76836ea62 to your computer and use it in GitHub Desktop.
Save rajnandan1/3c2c146466505f2fdeb82df76836ea62 to your computer and use it in GitHub Desktop.
Get card network and cvv length given a card number or bin
function getCardType(number) {
var res = {
id: null,
name: null
};
if (number.length <= 2) return res;
var re = new RegExp("^4");
if (number.match(re) != null) {
res.id = "visa";
res.name = "VISA";
res.cvvLength = 3;
}
// Mastercard
// Updated for Mastercard 2017 BINs expansion
if (/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(number)) {
res.id = "master";
res.name = "Mastercard";
res.cvvLength = 3;
}
// AMEX
re = new RegExp("^3[47]");
if (number.match(re) != null) {
res.id = "amex";
res.name = "Amex";
res.cvvLength = 4;
}
// Discover
re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)");
if (number.match(re) != null) {
res.id = "discover";
res.name = "Discover";
}
// Diners
re = new RegExp("^(36|38)");
if (number.match(re) != null) {
res.id = "diners";
res.name = "Diners";
res.cvvLength = 3;
}
// Diners - Carte Blanche
re = new RegExp("^30[0-5]");
if (number.match(re) != null) {
res.id = "diners";
res.name = "Diners - Carte Blanche";
res.cvvLength = 3;
}
// JCB
re = new RegExp("^35(2[89]|[3-8][0-9])");
if (number.match(re) != null) {
res.id = "jcb";
res.name = "JCB";
}
// Visa Electron
re = new RegExp("^(4026|417500|4508|4844|491(3|7))");
if (number.match(re) != null) {
res.id = "visa";
res.name = "Visa Electron";
res.cvvLength = 3;
}
//Rupay cards
var rupayRange = [
[508500, 508999],
[606985, 607384],
[607385, 607484],
[607485, 607984],
[608001, 608100],
[608101, 608200],
[608201, 608300],
[608301, 608350],
[608351, 608500],
[652150, 652849],
[652850, 653049],
[653050, 653149],
[353600, 353810],
[817200, 820199]
]
var bin = parseInt(number.substr(0, 6));
for (var _r = 0; !isNaN(bin) && (_r < rupayRange.length); _r++) {
if (rupayRange[_r][0] <= bin && bin <= rupayRange[_r][1]) {
res.id = "rupay";
res.name = "Rupay";
res.cvvLength = 3;
break;
};
}
return res;
}
console.log(getCardType("4111111111111111"))
/*
{
cvvLength: 3,
id: "visa",
name: "VISA"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment