Validating Email in C# using Regex on Server Side


This articles explain you how to validate email in C# using regex. Below is method to validate email:

protected bool IsValidEmail(string sEmail)
    {
      string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
        @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
        @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
      System.Text.RegularExpressions.Regex orgxEmail = new System.Text.RegularExpressions.Regex(strRegex);
      return orgxEmail.IsMatch(sEmail);
    }

Using the above method to validate a email textbox on button click:

protected void btnSubmit_Click(object sender, EventArgs e)
  {
    if (Emailcl.IsValidEmail(txtEmail.Text))
    {
      //Write code here if email is valid.
    }
    else
    {
      //Write code here if email is not valid.
    }
  }

Tags: , , , ,

Comments & Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

*


3 + 9 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>