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;
            ValidateEmail();
        }

        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;
        }

    }

         

Program.cs
**************

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


            EmailAddress emailAdd = "rajhseg@gmail.com";
            if (emailAdd.IsValid)
                Console.WriteLine(emailAdd + " is a valid Email");
            else
                Console.WriteLine(emailAdd + " is not valid Email");
         


Output:

rajeshgmail.com is not a valid Email
rajhseg@gmail.com 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