-1

我有这个功能很好,但是有没有更简单的方法来使用邮件地址类完成验证检查,它是否更合适。提前致谢。

        TextBox tb = new TextBox();
        tb.KeyDown += new KeyEventHandler(txtEmail_KeyDown);

        string strRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))";

        Regex re = new Regex(strRegex); // New regex Object  created 

        // Run Checks after the enter is pressed.
        if (e.KeyCode == (Keys.Enter))
        {
            // checks for is match, if empty and length 
            if (!re.IsMatch(txtEmail.Text) || (txtEmail.Text.Equals("")) || txtEmail.Text.Length > 100)
            {
                // display messagebox with error
                MessageBox.Show("Email not correct format!!!! ");
            }
            else
            {
                MessageBox.Show("Email Format is correct");
            }
        }

    }
4

2 回答 2

2

您可以像这样在 c# 中很容易地使用 EmailAddressAttribute 类进行验证

public bool ValidateEmail(string EmailToVerify)
{
  if (new EmailAddressAttribute().IsValid(EmailToVerify))
        return true;
  else 
        return false;
}

但是要使用它,您需要在 c# 代码页顶部添加它

using System.ComponentModel.DataAnnotations;

唯一的缺点是 EmailAdressAttribute 不是那么宽松,所以它取决于你想要限制和允许的内容

如果您需要,这里是有关此类的 msdn 文档的链接: https ://msdn.microsoft.com/fr-fr/library/system.componentmodel.dataannotations.emailaddressattribute(v=vs.110).aspx

于 2017-05-16T15:01:14.283 回答
0

不,它不稳定。由于其自身的任何正则表达式都代表一个有限状态机,因此在特殊情况下,它可能会进入一个无限循环,从而嫁接服务器的 DDOS 攻击。
只需使用 MailAddress 类进行验证。

更新 1
在测试MailAddress类之后,new EmailAddressAttribute().IsValid("MAIL_TEXT_HERE") 我得出结论,EmailAddressAttribute 的验证工作得更好。
您可以通过这种方式实现它,假设您有 TextBox 和 Button 用于提交。只需将此 Click 事件处理程序添加到按钮 Click 事件:

private void button1_Click(object sender, EventArgs e)
{
    if(!new EmailAddressAttribute().IsValid(textBox1.Text))
    {
        MessageBox.Show("Email is not valid");
    }
    else
    {
        MessageBox.Show("Email is valid");
    }
}
于 2017-05-16T14:46:03.400 回答