C# Windows 窗体上的电子邮件验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1558538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
e-mail validation on windows form
提问by user162558
i am using windows forms.
我正在使用 Windows 窗体。
I just want to validate my textbox ( or masked textbox ) for e-mail id.
我只想验证我的文本框(或掩码文本框)的电子邮件 ID。
Can any one tell me the idea for that?
任何人都可以告诉我这样做的想法吗?
回答by SteckCorporation
Try to use regular expression like
@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
尝试使用正则表达式,如
@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
回答by Frank Bollack
You can use the constructor of the System.Net.Mail.MailAdressclass that represents mail addresses.
您可以使用表示邮件地址的System.Net.Mail.MailAdress类的构造函数。
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
}
回答by maxy
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
{
}
回答by sudeep
string email=textbox1.text;
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]$");
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");`
回答by sudeep
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;
}
}
}
回答by Kervin Guzman
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;
}
}