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

            string valueAsString = value as string;
            return valueAsString != null && _regex.Match(valueAsString).Length > 0;
        }

Usage Example

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

            Assert.IsTrue(attribute.IsValid(null)); // Don't check for required
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsFalse(attribute.IsValid("foo"));
            Assert.IsFalse(attribute.IsValid("foo@"));
            Assert.IsFalse(attribute.IsValid("*****@*****.**"));
        }