System.ComponentModel.DataAnnotations.YearAttribute.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;
            var parseSuccess = int.TryParse(Convert.ToString(value), out retNum);

            return parseSuccess && retNum >= 1 && retNum <= 9999;
        }

Usage Example

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

            Assert.IsTrue(attribute.IsValid(null));
            Assert.IsTrue(attribute.IsValid("2011"));
            Assert.IsTrue(attribute.IsValid("9999"));
            Assert.IsTrue(attribute.IsValid(1234));
            Assert.IsTrue(attribute.IsValid(1111));
            Assert.IsTrue(attribute.IsValid(0123));
            Assert.IsTrue(attribute.IsValid("0123"));

            Assert.IsFalse(attribute.IsValid("one"));
            Assert.IsFalse(attribute.IsValid(""));
            Assert.IsFalse(attribute.IsValid(" "));
            Assert.IsFalse(attribute.IsValid("-100"));
            Assert.IsFalse(attribute.IsValid("20000"));
            Assert.IsFalse(attribute.IsValid(0));
        }