5

Before you mark this as answered in another post (I already saw those). But in none of them they specifically say the REGEX they suggest works for C# (I think they focus more on Javascript). Now I am not too good with regex but I would appreciate any help determining how to get the type and once I get the regex how can I validate the cc entered against the regex?

I saw this as an answer in many of the posts here in StackOverflow, but would this work in C# (same code) if yes how can i compare my creditCard string to the regex?

Get Card Type based on number

I would really appreciate any help, this is the first time i deal with credit card validation, just need to get the type. Drop down is out of the question based on the feedback from the person needing it.

user710502
  • 11,181
  • 29
  • 106
  • 161
  • Great, thank you so much for your prompt response. And if I were to compare the string entered to that regex, what would be the best way.. Like say if(ccText matches this expression) card_type = AMEX; – user710502 Feb 27 '12 at 15:51
  • You would use the `System.Text.RegularExpressions.Regex` class. Here's the documentation, it includes a tutorial (it might be a little complicated though - comment back if you have trouble): http://msdn.microsoft.com/en-us/library/ms228595(v=vs.80).aspx – Ry- Feb 27 '12 at 15:56
  • I'll try to be unique in my answer. They say it's better that you give a person a fishing rod than a fish. So my fishing rod is: Get [RegexBuddy](http://www.regexbuddy.com/). It's a great Regex editor that, among other things, shows you exactly how to write your regex in various languages, in various scenarios (search, replace, extract groups etc.). It's just perfect, except their technical support, although you'll rarely need it. – Ofer Zelig Feb 27 '12 at 15:51

4 Answers4

11

Here is a fuller answer for the next guy.

    public enum CardType
    {
        MasterCard, Visa, AmericanExpress, Discover, JCB
    };

    public static CardType FindType(string cardNumber)
    {
        //https://www.regular-expressions.info/creditcard.html
        if (Regex.Match(cardNumber, @"^4[0-9]{12}(?:[0-9]{3})?$").Success)
        {
            return CardType.Visa;
        }

        if (Regex.Match(cardNumber, @"^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$").Success)
        {
            return CardType.MasterCard;
        }

        if (Regex.Match(cardNumber, @"^3[47][0-9]{13}$").Success)
        {
            return CardType.AmericanExpress;
        }

        if (Regex.Match(cardNumber, @"^6(?:011|5[0-9]{2})[0-9]{12}$").Success)
        {
            return CardType.Discover;
        }

        if (Regex.Match(cardNumber, @"^(?:2131|1800|35\d{3})\d{11}$").Success)
        {
            return CardType.JCB;
        }

        throw new Exception("Unknown card.");
    }


    //test validation
    //https://www.getcreditcardnumbers.com/
    Validate("4169773331987017");//visa
    Validate("4658958254583145");//visa
    Validate("4771320594033780");//visa

    Validate("5410710000901089");//mc
    Validate("5289675573349651");//mc
    Validate("5582128534772839");//mc

    Validate("349101032764066");//ae
    Validate("343042534582349");//ae
    Validate("371305972529535");//ae

    Validate("6011683204539909");//discover
    Validate("6011488563514596");//discover
    Validate("6011465836488204");//discover

    Validate("3529908921371639");//jcb
    Validate("3589295535870728");//jcb
    Validate("3569239206830557");//jcb
hogarth45
  • 3,387
  • 1
  • 22
  • 27
7

Any of the regular expressions on that page will work in C#. For example:

string isVisa = "^4[0-9]{12}(?:[0-9]{3})?$";
string ccnumber = "1234123412341234";

if (System.Text.RegularExpressions.Regex.IsMatch(ccnumber, isVisa)) {
  // valid Visa card
}

A program I always recommend to test out regular expressions in C# is Expresso. You will be able to test out any of the credit card number validation patterns in that program.

ern
  • 1,522
  • 13
  • 19
1

Here is a fullerer answer to the previous person.

    public string CC_NUM { get; set; }

    /// <summary>
    /// getCardType()
    /// </summary>
    /// <returns>Matches a object reference to regex to bring back a card type, the validity of the card, or a default (Unknown)</returns>
    public CreditCardType getCardType()
    {
        return new Regex(@"^4[0-9]{6,}$").IsMatch(CC_NUM) ? CreditCardType.Visa :
               new Regex(@"^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$").IsMatch(CC_NUM) ? CreditCardType.MasterCard :
               new Regex(@"^3[47][0-9]{5,}$").IsMatch(CC_NUM) ? CreditCardType.AmericanExpress :
               new Regex(@"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$").IsMatch(CC_NUM) ? CreditCardType.Discover :
               new Regex(@"^3[47][0-9]{13}$").IsMatch(CC_NUM) ? CreditCardType.Amex :
               new Regex(@"^(6541|6556)[0-9]{12}$").IsMatch(CC_NUM) ? CreditCardType.BCGlobal :
               new Regex(@"^389[0-9]{11}$").IsMatch(CC_NUM) ? CreditCardType.CarteBlanch :
               new Regex(@"^3(?:0[0-5]|[68][0-9])[0-9]{11}$").IsMatch(CC_NUM) ? CreditCardType.DinersClub :
               new Regex(@"^63[7-9][0-9]{13}$").IsMatch(CC_NUM) ? CreditCardType.InstaPaymentCard :
               new Regex(@"^(?:2131|1800|35\d{3})\d{11}$").IsMatch(CC_NUM) ? CreditCardType.JCBCard :
               new Regex(@"^9[0-9]{15}$").IsMatch(CC_NUM) ? CreditCardType.KoreanLocal :
               new Regex(@"^(6304|6706|6709|6771)[0-9]{12,15}$").IsMatch(CC_NUM) ? CreditCardType.LaserCard :
               new Regex(@"^(5018|5020|5038|6304|6759|6761|6763)[0-9]{8,15}$").IsMatch(CC_NUM) ? CreditCardType.Maestro :
               new Regex(@"^(6334|6767)[0-9]{12}|(6334|6767)[0-9]{14}|(6334|6767)[0-9]{15}$").IsMatch(CC_NUM) ? CreditCardType.Solo :
               new Regex(@"^(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$").IsMatch(CC_NUM) ? CreditCardType.SwitchCard :
               new Regex(@"^(62[0-9]{14,17})$").IsMatch(CC_NUM) ? CreditCardType.UnionPay :
               CC_NUM.Where((e) => e >= '0' && e <= '9').Reverse().Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2)).Sum((e) => e / 10 + e % 10) == 0 ? CreditCardType.NotFormatted :
               CreditCardType.Unknown;
    }

    /// <summary>
    /// isCreditCardAccepted()
    /// </summary>
    /// <returns>Checks to see if the credit card is allowed by comparing it to the integer value of CreditCardType to a local array of allowed integers</returns>
    public bool isCreditCardAccepted()
    {
        // This should honestly be internalized somewhere for security reasons
        int[] allowed = new int[] { 0, 1, 2, 3 };
        return Array.IndexOf(allowed, getCardType()) >= 0;
    }

    public enum CreditCardType
    {
        Visa             = 0,
        MasterCard       = 1,
        AmericanExpress  = 2,
        Discover         = 3,
        Amex             = 4,
        BCGlobal         = 5,
        CarteBlanch      = 6,
        DinersClub       = 7,
        InstaPaymentCard = 8,
        JCBCard          = 9,
        KoreanLocal      = 10,
        LaserCard        = 11,
        Maestro          = 12,
        Solo             = 13,
        SwitchCard       = 14,
        UnionPay         = 15,
        NotFormatted     = 16,
        Unknown          = 17
    }
sheepiiHD
  • 421
  • 2
  • 16
0

Updated version with this regex

    public static CreditCardType GetCreditCardType(string CreditCardNumber)
    {
        Regex regAmex = new Regex("^3[47][0-9]{13}$");
        Regex regBCGlobal = new Regex("^(6541|6556)[0-9]{12}$");
        Regex regCarteBlanche = new Regex("^389[0-9]{11}$");
        Regex regDinersClub = new Regex("^3(?:0[0-5]|[68][0-9])[0-9]{11}$");
        Regex regDiscover = new Regex("^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$");
        Regex regInstaPayment = new Regex("^63[7-9][0-9]{13}$");
        Regex regJCB = new Regex(@"^(?:2131|1800|35\d{3})\d{11}$");
        Regex regKoreanLocal = new Regex("^9[0-9]{15}$");
        Regex regLaser = new Regex("^(6304|6706|6709|6771)[0-9]{12,15}$");
        Regex regMaestro = new Regex("^(5018|5020|5038|6304|6759|6761|6763)[0-9]{8,15}$");
        Regex regMastercard = new Regex("^(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}))$");
        Regex regSolo = new Regex("^(6334|6767)[0-9]{12}|(6334|6767)[0-9]{14}|(6334|6767)[0-9]{15}$");
        Regex regSwitch = new Regex("^(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$");
        Regex regUnionPay = new Regex("^(62[0-9]{14,17})$");
        Regex regVisa = new Regex("^4[0-9]{12}(?:[0-9]{3})?$");
        Regex regVisaMasterCard = new Regex("^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})$");

        if (regAmex.IsMatch(CreditCardNumber))
            return CreditCardType.AmericanExpress;
        else if (regBCGlobal.IsMatch(CreditCardNumber))
            return CreditCardType.BCGlobal;
        else if (regCarteBlanche.IsMatch(CreditCardNumber))
            return CreditCardType.CarteBlanche;
        else if (regDinersClub.IsMatch(CreditCardNumber))
            return CreditCardType.DinersClub;
        else if (regDiscover.IsMatch(CreditCardNumber))
            return CreditCardType.Discover;
        else if (regInstaPayment.IsMatch(CreditCardNumber))
            return CreditCardType.InstaPayment;
        else if (regJCB.IsMatch(CreditCardNumber))
            return CreditCardType.JCB;
        else if (regKoreanLocal.IsMatch(CreditCardNumber))
            return CreditCardType.KoreanLocal;
        else if (regLaser.IsMatch(CreditCardNumber))
            return CreditCardType.Laser;
        else if (regMaestro.IsMatch(CreditCardNumber))
            return CreditCardType.Maestro;
        else if (regMastercard.IsMatch(CreditCardNumber))
            return CreditCardType.Mastercard;
        else if (regSolo.IsMatch(CreditCardNumber))
            return CreditCardType.Solo;
        else if (regSwitch.IsMatch(CreditCardNumber))
            return CreditCardType.Switch;
        else if (regUnionPay.IsMatch(CreditCardNumber))
            return CreditCardType.UnionPay;
        else if (regVisa.IsMatch(CreditCardNumber))
            return CreditCardType.Visa;
        else if (regVisaMasterCard.IsMatch(CreditCardNumber))
            return CreditCardType.VisaMasterCard;
        else
            return CreditCardType.Invalid;
    }

And the enum:

public enum CreditCardType
{
    AmericanExpress,
    BCGlobal,
    CarteBlanche,
    DinersClub,
    Discover,
    InstaPayment,
    JCB,
    KoreanLocal,
    Laser,
    Maestro,
    Mastercard,
    Solo,
    Switch,
    UnionPay,
    Visa,
    VisaMasterCard,


    Invalid
}
A Petrov
  • 417
  • 1
  • 9
  • 23