Validate email address in C#

In this blog, let's see how how to validate email address in C#. We can use C# Regex class and regular expressions to validate an email in C#. The following Regex is an example to validate an email address in C#.
 
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$")
 
If you're new to C# regular expression, check out C# Regex Examples
 
Here is a simple ASP.NET page that uses C# Regex to validate an email address. 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Email_validation._Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7. <title>Untitled Page</title>  
  8. </head>  
  9. <body>  
  10. <form id="form1" runat="server">  
  11. <div>  
  12. <asp:TextBox runat="server" ID="txtemail"></asp:TextBox><br />  
  13. <asp:Button runat="server" ID="Validate" Text="Validate Email id"   
  14. onclick="Validate_Click" />  
  15. <asp:Label ID="lbl_message" runat="server" Font-Bold="True"   
  16. ForeColor="#CC3300"></asp:Label>  
  17. </div>  
  18. </form>  
  19. </body>  
  20. </html>  
  21.   
  22. using System;  
  23. using System.Collections;  
  24. using System.Configuration;  
  25. using System.Data;  
  26. using System.Linq;  
  27. using System.Web;  
  28. using System.Web.Security;  
  29. using System.Web.UI;  
  30. using System.Web.UI.HtmlControls;  
  31. using System.Web.UI.WebControls;  
  32. using System.Web.UI.WebControls.WebParts;  
  33. using System.Xml.Linq;  
  34. using System.Text.RegularExpressions;  
  35.   
  36. namespace Email_validation  
  37. {  
  38. public partial class _Default : System.Web.UI.Page  
  39. {  
  40.   
  41. private void ValidateEmail()  
  42. {  
  43. string email = txtemail.Text;  
  44. Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");  
  45. Match match = regex.Match(email);  
  46. if (match.Success)  
  47. lbl_message.Text=email + " is Valid Email Address";   
  48. else  
  49. lbl_message.Text = email + " is Invalid Email Address";  
  50. }  
  51.   
  52. protected void Validate_Click(object sender, EventArgs e)  
  53. {  
  54. ValidateEmail();  
  55. }  
  56. }  
  57. }