Created
February 22, 2012 17:01
-
-
Save jorgebastida/1886036 to your computer and use it in GitHub Desktop.
Get credit card type by number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks 👍
Converted to C#