System.ComponentModel.DataAnnotations.CreditCardAttribute.IsValid C# (CSharp) Method

IsValid() public method

Determines whether the specified value of the object is valid.
public IsValid ( object value ) : bool
value object The value of the object to validate.
return bool
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            var ccValue = value as string;
            if (ccValue == null)
            {
                return false;
            }

            ccValue = ccValue.Replace("-", string.Empty);

            if (string.IsNullOrEmpty(ccValue)) return false; //Don't accept only dashes

            int checksum = 0;
            bool evenDigit = false;

            // http://www.beachnet.com/~hstiles/cardtype.html
            foreach (char digit in ccValue.Reverse())
            {
                if (!Char.IsDigit(digit))
                {
                    return false;
                }

                int digitValue = (digit - '0') * (evenDigit ? 2 : 1);
                evenDigit = !evenDigit;

                while (digitValue > 0)
                {
                    checksum += digitValue % 10;
                    digitValue /= 10;
                }
            }

            return (checksum % 10) == 0;
        }

Usage Example

Esempio n. 1
0
		public void IsValid ()
		{
			var sla = new CreditCardAttribute ();

			Assert.IsTrue (sla.IsValid (null), "#A1-1");
			Assert.IsTrue (sla.IsValid (String.Empty), "#A1-2");
			Assert.IsFalse (sla.IsValid ("string"), "#A1-3");
			Assert.IsTrue (sla.IsValid ("378282246310005"), "#A1-4");
			Assert.IsTrue (sla.IsValid ("3782-8224-6310-005"), "#A1-5");
			Assert.IsTrue (sla.IsValid ("371449635398431"), "#A-6");
			Assert.IsFalse (sla.IsValid ("371449635498431"), "#A-6b");
			Assert.IsFalse (sla.IsValid (true), "#A1-7");
			Assert.IsFalse (sla.IsValid (DateTime.Now), "#A1-8");
		}
All Usage Examples Of System.ComponentModel.DataAnnotations.CreditCardAttribute::IsValid