예제 #1
0
        private CreditCard(string cardNumber, bool bypassChecks)
        {
            var trimmed = cardNumber?.Replace(" ", "");

            if (!bypassChecks && !string.IsNullOrEmpty(cardNumber))
            {
                if (trimmed.Length < 8)
                {
                    throw new ArgumentOutOfRangeException(nameof(cardNumber), Resources.CreditCard_MoreThan8Characters);
                }
                if (trimmed.Length > 19)
                {
                    throw new ArgumentOutOfRangeException(nameof(cardNumber), Resources.CreditCard_LessThan20Characters);
                }
                if (trimmed.Any(chr => !char.IsDigit(chr)))
                {
                    throw new ArgumentOutOfRangeException(nameof(cardNumber), Resources.CreditCard_OnlyDigits);
                }

                var algorithm = new LuhnChecksumCalculator();
                if (!algorithm.Validate(trimmed))
                {
                    throw new ArgumentOutOfRangeException(nameof(cardNumber), Resources.CreditCard_InvalidChecksum);
                }
            }
            _value = trimmed;
        }
예제 #2
0
        /// <summary>
        /// Try to parse the text to a credit card. Returns true when the parsing succeeds, false otherwise
        /// </summary>
        /// <param name="text">the text to parse</param>
        /// <param name="result">the resulting credit card</param>
        public static bool TryParse(string text, out CreditCard result)
        {
            var trimmed = text?.Replace(" ", "");

            if (string.IsNullOrEmpty(text))
            {
                result = new CreditCard();
                return(true);
            }
            if (!trimmed.All(char.IsDigit))
            {
                result = new CreditCard();
                return(false);
            }
            if (trimmed.Length < 8)
            {
                result = new CreditCard();
                return(false);
            }
            if (trimmed.Length > 19)
            {
                result = new CreditCard();
                return(false);
            }
            var algorithm = new LuhnChecksumCalculator();

            if (!algorithm.Validate(text))
            {
                result = new CreditCard();
                return(false);
            }

            result = new CreditCard(text);
            return(true);
        }