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})+)$")
Here is a simple ASP.NET page that uses C# Regex to validate an email address.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Email_validation._Default" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>Untitled Page</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:TextBox runat="server" ID="txtemail"></asp:TextBox><br />
- <asp:Button runat="server" ID="Validate" Text="Validate Email id"
- onclick="Validate_Click" />
- <asp:Label ID="lbl_message" runat="server" Font-Bold="True"
- ForeColor="#CC3300"></asp:Label>
- </div>
- </form>
- </body>
- </html>
-
- using System;
- using System.Collections;
- using System.Configuration;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Xml.Linq;
- using System.Text.RegularExpressions;
-
- namespace Email_validation
- {
- public partial class _Default : System.Web.UI.Page
- {
-
- private void ValidateEmail()
- {
- string email = txtemail.Text;
- Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
- Match match = regex.Match(email);
- if (match.Success)
- lbl_message.Text=email + " is Valid Email Address";
- else
- lbl_message.Text = email + " is Invalid Email Address";
- }
-
- protected void Validate_Click(object sender, EventArgs e)
- {
- ValidateEmail();
- }
- }
- }