1

What is a regular expression that I can use to prevent a textbox from accepting an email address?

NakedBrunch
  • 47,255
  • 13
  • 71
  • 97
Hiyasat
  • 7,972
  • 7
  • 31
  • 59

4 Answers4

4

Simply use a regex that is for an email address and check there are no matches.

Jamiec
  • 128,537
  • 12
  • 134
  • 188
4
Regex emailregex = new Regex("([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})");
String s = "johndoe@example.com";
Match m = emailregex.Match(s);
if (!m.Success) {
   //Not an email address
}

However, be very warned that others much smarter than you and I have not found the perfect regex for emails. If you want something bulletproof then stay away your current approach.

jdphenix
  • 14,226
  • 3
  • 39
  • 70
NakedBrunch
  • 47,255
  • 13
  • 71
  • 97
  • 1
    If you want a more comprehensive email address matching regex (RFC compliant) then try this ((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?) Short of verifying the domain, it covers most eventualities. More like this at http://www.regexlib.com – Lazarus Feb 02 '11 at 13:56
2

Read How to Find or Validate an Email Address and then check for no matches or negate the expression.

Nick Jones
  • 6,297
  • 2
  • 17
  • 18
1

It should be like this:

Regex emailRegex = new Regex(@"([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]    {1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})");
Match m = emailRegex.Match(this.emailAddress);
if (!m.Success) {
    MessageBox.Show("Email address is not correct");
} else { 
    Application.Exit();
}
Aoi Karasu
  • 3,635
  • 3
  • 34
  • 60
Evgeny
  • 11
  • 1