What is a regular expression that I can use to prevent a textbox from accepting an email address?
Asked
Active
Viewed 1,245 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 '@' ? – Henk Holterman 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? – Henk Holterman 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
- 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
-
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\-]+(?) 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