Skip to content

Instantly share code, notes, and snippets.

@jorgebastida
Created February 22, 2012 17:01
Show Gist options
  • Save jorgebastida/1886036 to your computer and use it in GitHub Desktop.
Save jorgebastida/1886036 to your computer and use it in GitHub Desktop.
Get credit card type by number
import re
def credit_card_type(number):
"""
Return a string that represents the type of the credit card number.
Criteria:
AMEX: Starts with 34 or 37 and the length 15.
MASTERCARD: Starts with 51-55 and the length is 16.
VISA: Starts with 4 and the length is 13 or 16.
DINNERSCLUB: Starts with 300-306 and the length is 14.
ENROUTE: Starts with 2014 or 2149 and the length is 15.
DISCOVER: Starts with 6011 and the length is 16.
If the number don't match with any criteria return None.
Inspired in this script: http://javascript.gakaa.com/credit-card-type-by-number.aspx
"""
number = re.sub(r'\s', '', number)
def tsrange(*args):
"""Returns a tuple of string"""
return tuple(map(str, range(*args)))
known_cards = [['AMEX', ('34', '37'), [15]],
['MASTERCARD', tsrange(51, 56), [16]],
['VISA', ('4'), [13, 16]],
['DINNERSCLUB', tsrange(300, 306), [14]],
['ENROUTE', ('2014', '2149'), [15]],
['DISCOVER', ('6011'), [16]],
['JCB', ('3'), [16]],
['JCB', ('2131', '1800'), [15]]]
for card_type, starts, length in known_cards:
if number.startswith(starts) and len(number) in length:
return card_type
return None
@bherila
Copy link

bherila commented Dec 4, 2015

Thanks 👍

Converted to C#

        private static int[] tsrange(int start, int end) {
            List<int> ints = new List<int>();
            for (int i = start; i <= end; ++i) {
                ints.Add(i);
            }
            return ints.ToArray();
        }

//---

            var knownCards = new[] {
                new {cardType = CardTypeAmex, starts = new[] {34, 37}, length = new[] {15}},
                new {cardType = CardTypeMastercard, starts = tsrange(51, 56), length = new[] {14}},
                new {cardType = CardTypeVisa, starts = new[] {4}, length = new[] {13, 16}},
                new {cardType = CardTypeDinersClub, starts = tsrange(300, 306), length = new[] {14}},
                new {cardType = CardTypeDiscover, starts = new[] {6011}, length = new[] {16}},
                new {cardType = CardTypeJcb, starts = new[] {3}, length = new[] {16}},
                new {cardType = CardTypeJcb, starts = new[] {2131, 1800}, length = new[] {15}}
            };
            foreach (var i in knownCards) {
                if (cardNumber.StartsWith(i.starts.ToString()) && i.length.Contains(cardNumber.Length))
                    return i.cardType;
            }

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