繁体   English   中英

Regex是否稳定,可用于对mailAddress类进行电子邮件验证?

[英]Is Regex stable to use for email validation oppsed to the mailAddress Class?

我具有此功能,但该功能运行良好,但是使用邮件地址类可以更轻松地完成验证检查,是否更合适。 提前致谢。

        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");
            }
        }

    }

您可以像这样在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

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

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

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");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM