//Say the text box's name as txtEmail
using System;
using System.Text.RegularExpressions;
private void txtEmail_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if(!ValidEmailAddress(txtEmail.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
txtEmail.Select(0, txtEmail.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(txtEmail, errorMsg);
}
}
private void txtEmail_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(txtEmail, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
// Confirm that the e-mail address string is not empty.
if(emailAddress.Length == 0)
{
errorMessage = "e-mail address is required.";
return false;
}
// Confirm that the e-mail address in correct regex format
if (Regex.IsMatch(emailAddress,
@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$")==false)
// Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
if(emailAddress.IndexOf("@") > -1)
{
if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") )
{
errorMessage = "";
return true;
}
}
errorMessage = "e-mail address must be valid e-mail address format.\n" +
"For example 'someone@example.com' ";
return false;
}