It is often required to get and store user
email through contact us form, login form etc. But it is also highly important
to check the validity of the Email address submitted by the user before storing
to ensure that the email address is valid.
Implementation: Let's check it out using an example
Asp.Net C# Code to check whether email address valid or not
First Include the namespace as:
using System.Text.RegularExpressions;
then write the code as:
public bool IsEmailValid(string Email)
{
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})(\\]?)$";
Regex re = new
Regex(strRegex);
if
(re.IsMatch(Email))
{
return true;
}
else
{
return
false;
}
}
Now just call this function and pass the email address as a
parameter to check whether it is valid or not. e.g. on Button Click event as:
protected void btnEmailCheck_Click(object sender, EventArgs
e)
{
if
(IsEmailValid("TestEmail@domain.com"))
{
Response.Write("Valid Email Id");
}
else
{
Response.Write("InValid Email Id");
}
}
VB.NET Code to check whether email address valid or not
First import namespace as:
imports System.Text.RegularExpressions
Public Function IsEmailValid(Email As String) As Boolean
Dim strRegex As
String = "^([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})(\]?)$"
Dim re As New
Regex(strRegex)
If re.IsMatch(Email)
Then
Return True
Else
Return False
End If
End Function
Now just call this function and pass the email address as a
parameter to check whether it is valid or not. e.g. on Button Click event as:
Protected Sub btnEmailCheck_Click(sender As Object, e As
EventArgs) Handles btnEmailCheck.Click
If
IsEmailValid("TestEmail@domain.com") Then
Response.Write("Valid Email Id")
Else
Response.Write("InValid Email Id")
End If
End Sub
0 comments:
Post a Comment