Sunday, 20 September 2015

Validate a Email Address when assign it from a string in C#

In this post we are going to see how to create a class which can validate a email address when it is assign from a string.

    public class EmailAddress
        Regex regex = new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.                                          [0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        public bool IsValid { set; get; }
        public string Address { set; get; }

        public EmailAddress(string value)
            Address = value;

        public static implicit operator EmailAddress(string value)
            return new EmailAddress(value);

        private void ValidateEmail()
            Match match = regex.Match(Address);
            IsValid = match.Success;

        public override string ToString()
            return Address;




            EmailAddress address = "";
            if (address.IsValid)
                Console.WriteLine(address + " is a valid Email");
                Console.WriteLine(address + " is not a valid Email");

            EmailAddress emailAdd = "";
            if (emailAdd.IsValid)
                Console.WriteLine(emailAdd + " is a valid Email");
                Console.WriteLine(emailAdd + " is not valid Email");

Output: is not a valid Email is a valid Email

From this post you can understand that how to create a class which can validate an email address.

No comments:

Post a Comment