What is a regular expression that I can use to prevent a textbox from accepting an email address?
Asked
Active
Viewed 1,290 times
1
-
3`[^@]+` won't match a modern email address. – Frédéric Hamidi Feb 02 '11 at 13:39
-
Good validation doesn't reject things but specifies what _is_ allowed. Will your texts contain '@' ? – H H Feb 02 '11 at 13:41
-
An additional criteria would be: Do you mean that the whole string cannot be an email address or that it can't contain an email address? – Lazarus Feb 02 '11 at 13:44
-
@Lazarus, the string can't contain an email address – Hiyasat Feb 02 '11 at 13:53
-
And do you have max/min length, what char sets, spaces allowed? – H H Feb 02 '11 at 14:00
-
I'd suggest reading this question with it's answers: [What is the best regular expression for validating email addresses?](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses) – Hans Olsson Feb 02 '11 at 14:08
4 Answers
4
Simply use a regex that is for an email address and check there are no matches.

Jamiec
- 133,658
- 13
- 134
- 193
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
- 15,022
- 3
- 41
- 74

NakedBrunch
- 48,713
- 13
- 73
- 98
-
1If 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\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>) 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,413
- 2
- 18
- 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,730
- 3
- 37
- 61

Evgeny
- 11
- 1