簡體   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