Friday 4 October 2013

Email validation with Regular Expression using C#



In this article I will explain how to validate Email with Regular expression in C#.NET

To validate email address we need to write the regular expression like this


bool isEmail = Regex.IsMatch(txtEmail.Text.Trim(), @"\A(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\Z");

If you want to see it in complete example write the following code in your aspx page like as shown below


<html>
<head>
<title>Regular Expression to validate Email Address</title>
</head>
<body>
<form id="Regular" runat="server">
<table>
<tr>
<td><b>Enter Email:</b></td>
<td>
<asp:TextBox ID="txtEmailId" runat="server" />
</td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnValidate" runat="server" Text="Validate Email"
onclick="btnValidate_Click" /> </td>
</tr>
</table>
<asp:label id="lblerrormsg" runat="server" style=" font-weight:bold" />
</form>
</body>
</html>

Once we write the code in aspx page add following namespaces in your code behind file
using System;
using System.Text.RegularExpressions;
Now write the following code in your code behind file 
protected void btnValidate_Click(object sender, EventArgs e)
{
bool isEmail = Regex.IsMatch(txtEmail.Text.Trim(), @"\A(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\Z");
if (!isEmail)
{
lblerrormsg.Text = "Enter Valid Email ID..";
lblerrormsg.ForeColor = System.Drawing.Color.Red;
return;
}
else
{
lblerrormsg.Text = "Valid Email";
lblerrormsg.ForeColor = System.Drawing.Color.Green;
}
}

No comments:

Post a Comment