Skip to content

Instantly share code, notes, and snippets.

@ryanhamley
Last active August 29, 2015 14:21
Show Gist options
  • Save ryanhamley/010a9cacf65b17db4572 to your computer and use it in GitHub Desktop.
Save ryanhamley/010a9cacf65b17db4572 to your computer and use it in GitHub Desktop.
Javascript function to determine a credit card type by its number.
//This function makes use of the getDigitAt() method which is found in a gist here: https://gist.github.com/ryanhamley/73140d5e9710a9a71fa0
function verifyCardType (_num) {
//cast primitive number _num to a Number object to allow for using the getDigitAt() method
var num = Number(_num);
if (num.getDigitAt(0) === 4) {
return 'Visa';
}
switch (num.getDigitAt(0, 2)) {
case 34:
case 37:
return 'American Express';
case 35:
return 'JCB';
case 36:
case 38:
return 'Diner\'s Club';
case 51:
case 52:
case 53:
case 54:
case 55:
return 'MasterCard';
case 65:
return 'Discover';
}
switch (num.getDigitAt(0, 3)) {
case 300:
case 301:
case 302:
case 303:
case 304:
case 305:
return 'Diner\'s Club';
}
switch (num.getDigitAt(0, 4)) {
case 2131:
case 1800:
return 'JCB';
case 6011:
return 'Discover';
}
//if none of the above, return 'Unknown';
return 'Unknown';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment