Reputation: 259
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?
Upvotes: 2
Views: 32733
Reputation: 151
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;
}
}
Upvotes: 1
Reputation:
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;
}
}
}
Upvotes: 1
Reputation: 126
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");`
Upvotes: 1
Reputation: 438
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
{
}
Upvotes: 2
Reputation: 25166
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
}
Upvotes: 4
Reputation: 51
Try to use regular expression like
@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Upvotes: 4