System.ComponentModel.DataAnnotations.IntegerAttribute.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;

            int retNum;

            return int.TryParse(Convert.ToString(value), out retNum);
        }

Usage Example

        public void IsValidTests()
        {
            var attribute = new IntegerAttribute();

            Assert.IsTrue(attribute.IsValid(null)); // Don't check for required
            Assert.IsTrue(attribute.IsValid("1234"));
            Assert.IsTrue(attribute.IsValid("12345"));
            Assert.IsTrue(attribute.IsValid(14));
            Assert.IsTrue(attribute.IsValid(-10)); //Allows negative numbers
            Assert.IsTrue(attribute.IsValid("-50"));
            Assert.IsFalse(attribute.IsValid(14.50));
            Assert.IsFalse(attribute.IsValid("12.90"));
            Assert.IsFalse(attribute.IsValid("1234.5"));
            Assert.IsFalse(attribute.IsValid("$3.50"));
            Assert.IsFalse(attribute.IsValid("12abc"));
            Assert.IsFalse(attribute.IsValid(DateTime.Now));
            Assert.IsFalse(attribute.IsValid("fourteen"));
        }