Sponsored Ad

Sunday, June 13, 2010

How to Validate Credit Card in C#

While wi=orking with financial applications, sometimes we need to validate creadit card number. You can easily validate creadit card number.

This C# code block will check the validity for

  1. MasterCard
  2. American Express
  3. Visa

Cards. So just copy this code and pass the card type and card number. This function will return true if card is valid and false if card is invalid.

 

How to Validate Credit Card in C# Example

public bool Validate_Credit_Card(string card_type, string card_number)
    {
        byte[] bNumber = new byte[16];
        int intLength = 0;
        for (int i = 0; i < card_number.Length; i++)
        {
            if (char.IsDigit(card_number, i))
            {
                if (intLength == 16) return false;
                bNumber[intLength++] = byte.Parse(card_number[i].ToString());
            }

        }

        switch (card_type)
        {
            case "MasterCard":
                if (intLength != 16)
                    return false;
                if (bNumber[0] != 5 || bNumber[1] == 0 || bNumber[1] > 5)
                    return false;
                break;

            case "AmericanExpress":
                if (intLength != 15)
                    return false;
                if (bNumber[0] != 3 || (bNumber[1] != 4 && bNumber[1] != 7))
                    return false;
                break;

            case "Visa":
                if (intLength != 16 && intLength != 13)
                    return false;
                if (bNumber[0] != 4)
                    return false;
                break;
        }

        int sum = 0;
        for (int i = intLength - 1; i >= 0; i--)
        {
            if (i % 2 == intLength % 2)
            {
                int n = bNumber[i] * 2;
                sum += (n / 10) + (n % 10);
            }
            else
                sum += bNumber[i];
        }
        if (sum == 0)
        {
            return false;

        }
        else
        {
            return (sum % 10 == 0);
        }

    }

0 comments:

Post a Comment

Sponsored Ad

More Related Articles

Website Update

Followers