コード例 #1
0
        /// <summary>
        /// Validates the passed-in card, making sure that the card is not expired
        /// and that it passed the Luhn Algorigthm
        /// </summary>
        /// <param name="card">The Credit Card to validate</param>
        public bool IsValid()
        {
            bool isValid = false;

            isValid = Expiration >= DateTime.Today;

            if (isValid)
            {
                //string empty cars, and set to an array
                char[] cardChars = AccountNumber.Replace(" ", "").ToCharArray();

                int  sum          = 0;
                int  currentDigit = 0;
                bool alternate    = false;

                //use the Luhn Algorithm to validate the card number
                //http://en.wikipedia.org/wiki/Luhn_algorithm
                //count from left to right
                for (int i = cardChars.Length - 1; i >= 0; i--)
                {
                    if (alternate)
                    {
                        if (int.TryParse(cardChars[i].ToString(), out currentDigit))
                        {
                            currentDigit *= 2;
                            if (currentDigit > 9)
                            {
                                currentDigit -= 9;
                            }
                        }
                        else
                        {
                            // non-int character
                            return(false);
                        }
                    }
                    sum      += currentDigit;
                    alternate = !alternate;
                }

                isValid = sum % 10 == 0;
            }
            return(isValid);
        }