Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Regular Expression for Email Validation in C#

I have seen a multitude of regular expressions for different programming languages that all purport to validate email addresses. I have seen many comments saying that the expressions in question do not work for certain cases and that they are either too strict or too permissive. What I'm looking for is a regular expression that I can use in my C# code that is definitive.

The best thing I have found is this

^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$ 

Is there something better?

like image 549
Sachin Kainth Avatar asked Apr 23 '13 11:04

Sachin Kainth


People also ask

What is the simplest regular expression for email validation in C?

Regex : ^(.+)@(.+)$ This one is simplest and only cares about '@' symbol. Before and after '@' symbol, there can be any number of characters.

What is the regex for email?

[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times. @ matches itself.

Should you validate email with regex?

Don't use regexes for validating emails, unless you have a good reason not to. Use a verification mail instead. In most cases, a regex that simply checks that the string contains an @ is enough.


2 Answers

Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])? 

Usage :

bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase); 
like image 155
Parimal Raj Avatar answered Sep 17 '22 09:09

Parimal Raj


First option (bad because of throw-catch, but MS will do work for you):

bool IsValidEmail(string email) {     try {         var mail = new System.Net.Mail.MailAddress(email);         return true;     }     catch {         return false;     } } 

Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification

like image 42
Piotr Stapp Avatar answered Sep 17 '22 09:09

Piotr Stapp