How to use a separate class to validate credit card numbers in C#

Posted by EvanRyan on Stack Overflow See other posts from Stack Overflow or by EvanRyan
Published on 2010-05-11T21:06:20Z Indexed on 2010/05/11 21:14 UTC
Read the original article Hit count: 258

Filed under:
|
|
|

I have set up a class to validate credit card numbers. The credit card type and number are selected on a form in a separate class. I'm trying to figure out how to get the credit card type and number that are selected in the other class (frmPayment) in to my credit card class algorithm:

public enum CardType
{
    MasterCard, Visa, AmericanExpress
}

public sealed class CardValidator
{
    public static string SelectedCardType { get; private set; }
    public static string CardNumber { get; private set; }

    private CardValidator(string selectedCardType, string cardNumber) 
    {
        SelectedCardType = selectedCardType;
        CardNumber = cardNumber;
    }

    public static bool Validate(CardType cardType, string cardNumber)
{
   byte[] number = new byte[16];


  int length = 0;
  for (int i = 0; i < cardNumber.Length; i++)
  {
      if (char.IsDigit(cardNumber, i))
      {
          if (length == 16) return false;
          number[length++] = byte.Parse(cardNumber[i]); //not working.  find different way to parse
      }
  }

  switch(cardType)
  {
     case CardType.MasterCard:
        if(length != 16)
           return false;
        if(number[0] != 5 || number[1] == 0 || number[1] > 5)
           return false;
        break;

     case CardType.Visa:
        if(length != 16 & length != 13)
           return false;
        if(number[0] != 4)
           return false;
        break;

     case CardType.AmericanExpress:
        if(length != 15)
           return false;
        if(number[0] != 3 || (number[1] != 4 & number[1] != 7))
           return false;
        break;

  }

  // Use Luhn Algorithm to validate
  int sum = 0;
  for(int i = length - 1; i >= 0; i--)
  {
     if(i % 2 == length % 2)
     {
        int n = number[i] * 2;
        sum += (n / 10) + (n % 10);
     }
     else
        sum += number[i];
  }
  return (sum % 10 == 0);

} }

© Stack Overflow or respective owner

Related posts about class

Related posts about enum