I have this function of which works fine however is there and easier way to complete the validation check using the mail address class, and would it be more fitting. Thanks in advance.
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");
}
}
}
No, it is not stable. Since any regular expression of itself represents a finite state machine, it can, in special cases, get into an infinite loop that grafts to the server's DDOS attack.
Just use MailAddress class for validation.
UPDATE 1
After testing
MailAddress
class andnew EmailAddressAttribute().IsValid("MAIL_TEXT_HERE")
I came to conclusion that EmailAddressAttribute's Validation is working better.You can implement it in this way, let's say that you have TextBox and Button for submit. Just add this Click event handler to buttons Click Event: