2

i am using windows forms.

I just want to validate my textbox ( or masked textbox ) for e-mail id.

Can any one tell me the idea for that?

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
user162558
  • 249
  • 3
  • 7
  • 11

6 Answers6

4

Try to use regular expression like @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

4

You can use the constructor of the System.Net.Mail.MailAdress class that represents mail addresses.

Try to initialize an instance with your string and catch the exception, that is thrown if the validation failed. Something like this:

try
{
   new System.Net.Mail.MailAddress(this.textBox.Text);
}
catch(ArgumentException)
{
   //textBox is empty
}
catch(FormatException)
{
   //textBox contains no valid mail address
}
Frank Bollack
  • 24,478
  • 5
  • 49
  • 58
2

try regular expression

@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

or check your email address in code

string email=textbox1.text;
if(email.lastindexof("@")>-1)
{
//valid
}
else
{

}
maxy
  • 438
  • 3
  • 10
  • 20
1

string email=textbox1.text;

System.Text.RegularExpressions.Regex expr= new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");

`if (expr.IsMatch(email))
            MessageBox.Show("valid");

        else MessageBox.Show("invalid");`
sudeep
  • 126
  • 1
  • 4
1

Try this:

private void emailTxt_Validating(object sender, CancelEventArgs e)

{

System.Text.RegularExpressions.Regex rEmail = new    System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");

        if (emailTxt.Text.Length > 0 && emailTxt.Text.Trim().Length != 0)
        {
            if (!rEmail.IsMatch(emailTxt.Text.Trim()))
            {
                MessageBox.Show("check email id");
                emailTxt.SelectAll();
                e.Cancel = true;
            }
        }
    }
Hulk1991
  • 3,079
  • 13
  • 31
  • 46
1

I recommend you use this way and it's working well for me.

/* Add this reference */

using System.Text.RegularExpressions;

---------------------------

if (!string.IsNullOrWhiteSpace(txtEmail.Text))
{
    Regex reg = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
    if (!reg.IsMatch(txtEmail.Text))
    {
        Mensaje += "* El email no es válido. \n\n";
        isValid = false;
    }
}
Kervin Guzman
  • 131
  • 1
  • 5