Sunday, November 8, 2009

Credit Card Validator in C#

I needed a credit card validator for a few of my projects. I found a few snippets of code throughout google, but nothing really just giving me what I needed, so I wanted to post my class. Maybe it will help others doing the same thing I did.

    public class CardValidator
    {
        public string CardType { get; private set; }
        public bool IsValid { get; private set; }
        public string ResultingError { get; private set; }
       
        public string CardNumber { get; set; }
        public DateTime CardExpiration { get; set; }

        public void Validate()
        {
            IsValid = false;

            if (string.IsNullOrEmpty(CardNumber))
            {
                ResultingError = "Card number empty....";
                return;
            }

            if (CardNumber.Length > 16)
            {
                ResultingError = "Card number too long";
                return;
            }

            foreach (char digit in CardNumber)
            {
                if (!char.IsDigit(digit))
                {
                    ResultingError = "Card number contains invalid characters";
                    return;
                }
            }

            if (CardExpiration < DateTime.Today)
            {
                ResultingError = "Card has expired.";
                return;
            }

            int sum = 0;
            for (int i = CardNumber.Length - 1; i >= 0; i--)
            {
                if (i % 2 == CardNumber.Length % 2)
                {
                    int n = int.Parse(CardNumber.Substring(i, 1)) * 2;
                    sum += (n / 10) + (n % 10);
                }
                else
                {
                    sum += int.Parse(CardNumber.Substring(i, 1));
                }
            }

            IsValid = (sum % 10 == 0);

            if (IsValid == true)
            {
                switch (CardNumber.Substring(0, 1))
                {
                    case "3":
                        CardType = "AMEX/Diners Club/JCB";
                        break;
                    case "4":
                        CardType = "VISA";
                        break;
                    case "5":
                        CardType = "MasterCard";
                        break;
                    case "6":
                        CardType = "Discover";
                        break;
                    default:
                        CardType = "Unknown";
                        break;
                }
            }
            else
            {
                CardType = "Invalid";
            }
        }
    }