Monday, 15 April 2013 13:56

how to validate a email address by c#

Written by 
Rate this item
(0 votes)

It's a very logical requirement to validate user entered email
address before processing anything.in this way you will
never get a invalid email address when you do something
with email address like send email,etc.

using customvalidator control you can validate a email -

<asp:TextBox ID="FirstEstimatorEmail" CssClass="textbox_style" Width="150px" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator11" runat="server"
ControlToValidate="FirstEstimatorEmail" ErrorMessage="Invalid email address.
Please enter a valid email address." ValidationGroup="buttongroup"
onservervalidate="CustomValidatorEst1Email_ServerValidate"
ValidateEmptyText="True">&nbsp *</asp:CustomValidator>

in code behind page -

protected void CustomValidatorEst1Email_ServerValidate(object source, ServerValidateEventArgs args)
{
if (FirstEstimatorEmail.Text.Length < 1) { //do nothing }
else
{
Regex EmailRegex = new Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)
*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");

if (EmailRegex.IsMatch(FirstEstimatorEmail.Text.Trim()))
{
//email ok
}
else
args.IsValid = false;
}
}

regards..

Read 3469 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.
More in this category: « how to use verbatim string

Latest discussions

  • No posts to display.