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. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head runat="server">
  5. <title>Untitled Page</title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <asp:TextBox runat="server" ID="txtemail"></asp:TextBox><br />
  11. <asp:Button runat="server" ID="Validate" Text="Validate Email id"
  12. onclick="Validate_Click" />
  13. <asp:Label ID="lbl_message" runat="server" Font-Bold="True"
  14. ForeColor="#CC3300"></asp:Label>
  15. </div>
  16. </form>
  17. </body>
  18. </html>
  19. using System;
  20. using System.Collections;
  21. using System.Configuration;
  22. using System.Data;
  23. using System.Linq;
  24. using System.Web;
  25. using System.Web.Security;
  26. using System.Web.UI;
  27. using System.Web.UI.HtmlControls;
  28. using System.Web.UI.WebControls;
  29. using System.Web.UI.WebControls.WebParts;
  30. using System.Xml.Linq;
  31. using System.Text.RegularExpressions;
  32. namespace Email_validation
  33. {
  34. public partial class _Default : System.Web.UI.Page
  35. {
  36. private void ValidateEmail()
  37. {
  38. string email = txtemail.Text;
  39. Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
  40. Match match = regex.Match(email);
  41. if (match.Success)
  42. lbl_message.Text=email + " is Valid Email Address";
  43. else
  44. lbl_message.Text = email + " is Invalid Email Address";
  45. }
  46. protected void Validate_Click(object sender, EventArgs e)
  47. {
  48. ValidateEmail();
  49. }
  50. }
  51. }