Quick Tip: Validate email address in C#.NET with Regular Expressions

Ok so this is no biggie, but sure comes useful at some point when dealing with any kind of form input validation. Actually I just found myself in the needs of such validation snippet but didn’t have any at hand, so after a while putting it together I figured what better place to store for future references than my blog!

The pattern for the regular expression I borrowed from this cheat sheet. It works very nice except for some extreme cases like one-character domain, although it does reject one-character top-level domain, but I’m sure it’d be pretty easy to adjust to specific needs.

So here’s the snippet code:

private Boolean isValidEmail(String email)
{
	Regex reg = new Regex(@"(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})");
	return reg.IsMatch(email);
}

0 comments: