C# code to validate email address
Solution 1
What about this?
bool IsValidEmail(string email)
{
var trimmedEmail = email.Trim();
if (trimmedEmail.EndsWith(".")) {
return false; // suggested by @TK-421
}
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == trimmedEmail;
}
catch {
return false;
}
}
Per Stuart's comment, this compares the final address with the original string instead of always returning true. MailAddress tries to parse a string with spaces into "Display Name" and "Address" portions, so the original version was returning false positives.
To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.
Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:
- cog@wheel
- "cogwheel the orange"@example.com
- 123@$.xyz
For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.
Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow 🌮🍳🎁 as an email address."
As for using exception handling for business logic, I agree that is a thing to be avoided. But this is one of those cases where the convenience and clarity may outweigh the dogma.
Besides, if you do anything else with the e-mail address, it's probably going to involve turning it to a MailAddress. Even if you don't use this exact function, you will probably want to use the same pattern. You can also check for specific kinds of failure by catching different exceptions: null, empty, or invalid format.
--- Further reading ---
Documentation for System.Net.Mail.MailAddress
Explanation of what makes up a valid email address
Solution 2
This is an old question, but all the answers I've found on SO, including more recent ones, are answered similarly to this one. However, in .Net 4.5 / MVC 4 you can add email address validation to a form by adding the [EmailAddress] annotation from System.ComponentModel.DataAnnotations, so I was wondering why I couldn't just use the built-in functionality from .Net in general.
This seems to work, and seems to me to be fairly elegant:
using System.ComponentModel.DataAnnotations;
class ValidateSomeEmails
{
static void Main(string[] args)
{
var email = new EmailAddressAttribute();
email.IsValid("[email protected]"); //true
email.IsValid("[email protected]"); //true
email.IsValid("[email protected]"); //true
email.IsValid("[email protected]"); //true
email.IsValid("fdsa"); //false
email.IsValid("fdsa@"); //false
email.IsValid("fdsa@fdsa"); //false
email.IsValid("fdsa@fdsa."); //false
//one-liner
if (new EmailAddressAttribute().IsValid("[email protected]"))
return true;
}
}
Solution 3
I use this single liner method which does the work for me-
using System.ComponentModel.DataAnnotations;
public bool IsValidEmail(string source)
{
return new EmailAddressAttribute().IsValid(source);
}
Per the comments, this will "fail" if the source
(the email address) is null.
public static bool IsValidEmailAddress(this string address) => address != null && new EmailAddressAttribute().IsValid(address);
Solution 4
.net 4.5 added System.ComponentModel.DataAnnotations.EmailAddressAttribute
You can browse the EmailAddressAttribute's source, this is the Regex it uses internally:
const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
Solution 5
I took Phil's answer from #1 and created this class.
Call it like this: bool isValid = Validator.EmailIsValid(emailString);
Here is the class:
using System.Text.RegularExpressions;
public static class Validator
{
static Regex ValidEmailRegex = CreateValidEmailRegex();
/// <summary>
/// Taken from http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
/// </summary>
/// <returns></returns>
private static Regex CreateValidEmailRegex()
{
string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
return new Regex(validEmailPattern, RegexOptions.IgnoreCase);
}
internal static bool EmailIsValid(string emailAddress)
{
bool isValid = ValidEmailRegex.IsMatch(emailAddress);
return isValid;
}
}
leora
Updated on December 18, 2021Comments
-
leora over 2 years
What is the most elegant code to validate that a string is a valid email address?
-
Luke Quinane almost 15 yearsI liked you list of alternative approaches; very interesting.
-
Luke Quinane almost 15 yearsI personally think you should do a bit more validation than that. Someone's bound to try Bobby Table's email address or worse.
-
Kibbee almost 15 yearsWhat's wrong with bobby table's email address if you're using prepared statements. We're talking about valid email addresses, not other things that have nothing to do with what constitues a valid email address, like how to properly do SQL queries so that you don't get SQL injection problems.
-
Matthew Lock almost 15 yearsInteresting article. But seriously who's putting comments, and nested ones at that, in email addresses?
-
Mauricio Scheffer almost 15 years@matthew I don't know why the IETF has even allowed that, but it's possible, so a thorough validation has to take it into account.
-
Kibbee almost 15 yearsThat's for the mail system to worry about. I wouldn't go around rejecting perfectly valid email addresses just because it could be a security issue with some other system. If all your email server needs is a malformed email address to cause security problems, you should probably switch to another server.
-
Mouffette over 14 yearsi don't think it works. i just tried it with simply a@a and it returned true. thats wrong.
-
Cogwheel over 14 yearsActually, that's not incorrect. a@a is a valid e-mail address. See haacked.com/archive/2007/08/21/… In fact, this method does return incorrect results if you use an address with quotes.
-
Meydjer Luzzoli over 14 years+1: This is the best answer if you're using the
System.Net.Mail
classes to send mail, which you probably are if you're using .NET. We made the decision to use this type of validation simply because there is no point in us accepting email addresses - even valid ones - that we cannot send mail to. -
Kakashi over 12 yearsI don't recommend. It returns true:
IsValidEmail("this is not valid@email$com");
-
Cogwheel about 12 years@Kakashi: See the link I posted above. If you follow up by checking the RFC, you'll see "Any characters, or combination of bits (as octets), are permitted in DNS names. However, there is a preferred form that is required by most applications." In other words, it's only convention that makes that address invalid. You could always use the MailAddress object this code creates and further validate the Host part.
-
Mark A almost 12 yearsDid you create fakes, stubs and/or mocks for those interfaces?
-
Dan Balthaser over 11 yearsThe only reason I don't like this solution is that it relies on exception handling which is slow and bad practice in my book. Is there any way around this problem for this particular solution? I haven't been able to find one.
-
Cogwheel over 11 yearsI've ranted about using exceptions for business logic before, but I think in the context it's fine. It's a straightforward way of getting the job done without reinventing the wheel. If it turns out to be a performance issue, then I'd be inclined to go with Kibbee's suggestion.
-
Bastien Vandamme over 11 yearsI don't like the idea to create an object in memory to validating something. @Dan Balthaser throwing exception is a good practice, but you should only catch them when required.
-
Andreas over 11 yearsThis one does no validation, and is useless.
-
Cogwheel over 11 years@Andreas I think you have a different idea of what "validation" means in the context of this question. Just because a string is a valid e-mail address, doesn't mean the e-mail address actually exists on a server somewhere. If that's not what you meant, then I suggest you read all the comments above and the article linked in the accepted answer.
-
Chad Grant almost 11 yearsMy first test of this code, IsValidEmail("xxx@u*.com") = true, which is obviously wrong. Not to mention using exceptions for control flow :(
-
Cogwheel almost 11 yearsThat's not obviously wrong if you read the spec. The question was about whether a particular string is a valid representation of an e-mail address, not whether that e-mail address is likely to exist on a server somewhere.
-
B Z almost 11 yearsUnfortunately the EmaillAddressAttribute allows Ñ which is not a valid character for email
-
Chad Grant almost 11 yearsThat won't work. The smtp protocol to verify an email address has LONG been deprecated/not used. It is considered bad practice to enable that on mail servers since spammers use that functionality.
-
Marc over 10 yearsJust a small one, but I would use: return (!string.IsNullOrEmpty(emailAddress)) && ValidEmailRegex.IsMatch(emailAddress);
-
ManicDee over 10 yearsDefence in depth only works if each level of your security onion is not rotten. One rotten layer means you spoil the whole onion. Rejecting "[email protected]" because you want to defend against vulnerabilities in Sun's µ-law encoding doesn't make sense, does it? Don't laugh, it's happened to me. The reason I am here commenting is that Medicare Australia doesn't allow ".au" addresses, only ".com". Also read Mark Swanson, "How not to validate email, ", mdswanson.com/blog/2013/10/14/…
-
Fattie over 10 yearsthat seems to be the best most thoughtful / reasonable / realworld answer, thanks Ralph!
-
ta.speot.is about 10 yearsI'm confused as to why everybody keeps saying
MailAddress
has it right."test [email protected]"
come back as valid and I can't find anything in the spec that says you can have an unescaped space character in the local part of the name. -
Cogwheel about 10 yearsMailAddress may get some things wrong from the RFC, but most of the comments are about things it gets right that people assume are wrong. Either way, if you're in the .Net environment, this is the best way to ensure that you have an address that will be accepted by System.Net.Mail.
-
Doug S about 10 years-1 I have to agree with the others, that though this answer is technically right according to the RFC spec (actually it doesn't even do that according to the 2 comments above me), it is incorrect to the spirit of the original question since this answer considers valid so many addresses that would actually fail in reality. A standard RegEx is more appropriate to answer the spirit of the original question.
-
Doug S about 10 years-1 Besides using an
Exception
for validation,System.Net.Mail.MailAddress
approves way too many string combinations that would fail in reality and are also wrong according to the RFC spec, such asunescaped white space@fake$com
. -
Stuart about 10 yearsA lot of the problems seem to be because MailAddress tries to parse the DisplayName out too, so "single [email protected]" parses to DisplayName "single" and Address "[email protected]". A fix for this is to: return (addr.Address == email);
-
Cogwheel about 10 years@DougS: Your second comment is addressed in the latest edit. Your first comment seems a bit odd... If you want to know whether an e-mail address will fail, the only sure way is to try sending it a message. You have to make a lot of assumptions about your environment to assume the addresses you think are invalid will always be invalid. As soon as one of those assumptions is broken you will have to fix your code.
-
Doug S about 10 years@Cog: I'm not saying I "want to know whether an e-mail address will fail" in advance, as I know that's practically impossible to know. My comment simply means that when we're trying to estimate whether a string looks like a good email address in the real world, this code fails a lot more often than a well-written RegEx.
-
Cogwheel about 10 years@DougS The real world is constantly changing. You can't predict where your code will be used in the future (maybe in an environment that uses internal domains that wouldn't exist on the public internet?), what TLDs will exist in the future, what kinds of addresses e-mail providers support, and on and on. For general applicability, the fewer assumptions you make in a function like this the better, imo. As an answer to the question posed, I fail to see how this is wrong. The asker didn't specify any of the assumptions you're making and accepted the most pedantic of all the given answers.
-
Doug S about 10 years@Cogwheel It's not a wrong answer, depending on the application. For the majority of applications, however, the negatives outweigh the elegance, and it's better to go with another solution such as RegEx.
-
Casey almost 10 yearsI like this; I don't get the compulsion to be more restrictive than the actual spec. False negatives are way worse than false positives ("what do you mean my e-mail is invalid?")
-
Casey almost 10 yearsCool, although it's disappointing that MS can't make this agree with their own documentation. This rejects [email protected]
-
Casey almost 10 years@BZ Yes it is. Why do you think it isn't?
-
Jim over 9 yearsThis is a great solution; why reinvent the wheel with code to determine what a valid email address is when you can instead just let .NET do it for you? Although I'm not inclined to trust Microsoft on much these days, this is one area where I'd gladly let them decide what's valid and what's not. If this doesn't fit your needs, don't cry about it in comments, just go use a RegEx. The fact remains, this will probably fit the needs of 90% of the people who Google "Validate email address in .NET".
-
Bob.at.Indigo.Health over 9 yearsIf you use [EmailAddress] in your view model (as I do), this is a slick way to ensure that you use the same validation logic -- for better or worse -- in your code.
-
Moh over 9 yearsI have read all the comments and found out that many of the users have declined your answer without even testing it or reading the specs. I checked space in the address, it doesn't accept spaces in the email address, but there are many comments complaining about spaces in comments. I would recommend using it. But the only drawback is that we don't have any idea about the code behind it, therefore it would be a bit wiser if one chooses to use a RegEx pattern. I have compared many results of your answer with the results of Haack's proposed RegEx. They have the same performance in many cases
-
Moh over 9 yearsAccording to the spec, your answer works better, but according to the conventions made on mail servers, Haack's RegEx is more realistic.
-
Aaroninus over 9 yearsNote that
EmailAddressAttribute
is less permissive thanSystem.Net.Mail.MailAddress
- for instance,MailAddress
accepts an address for a TLD. Just something to keep in mind if you need to be as permissive as possible. -
Cogwheel over 9 years@MohammadAliannejadi I see what you're saying but i think that logic is reversed. When you're validating an e-mail address, it's almost certainly because someone gave it to you expecting you to send them e-mail. In that case, you definitely DON'T want to just cater to "the conventions made on mail servers." As others have stated, if you want to ensure that your message will be received, the only reliable way is to send a test message.
-
MonsterMMORPG about 9 yearsit says true for this email : "[email protected]ö" and it throws error at mandrill api
-
Aina Ademola C about 9 yearsFirst, the email is valid w.r.t. [email protected] or [email protected] email has all valid string and criterial except for the last character " ö " and you can easily add a simple condition to validate such character. Second, am not sure about that mandrill api error, you might want to verify your method of usage bcos I have used this validation on some other environment / api's and its been good to me.
-
disasterkid almost 9 yearsthis is the best answer so far! I can't believe a bad solution that accepts
basket@ball
as a valid email address has gained the correct answer as well as all those upvotes. Thanks anyway! -
Nikhil Agrawal over 8 years@Chad Grant: This is a C# version. Can you please provide a VB.Net one. Because that will escape characers like \\ to \ or you can provide a string verbatim one.
-
Matthew Lock over 8 yearsImpressive! "Next, it tries to contact the mail exchanger responsible for the given email address and begins a fake SMTP dialog with that server, emulating a real mail server. This way it ensures that the server can handle emails for the address. Many SMTP servers actually give back false positive answers as a protection against spammers: to overcome this issue, EmailVerify for .NET finally attempts to query the target mail exchanger multiple times with different fabricated addresses. "
-
Efran Cobisi over 8 yearsThanks, @MatthewLock ;)
-
Cogwheel over 8 years@hofnarwillie: yes, because that is a valid e-mail address. See the link in and comments on my answer.
-
hofnarwillie over 8 years@Cogwheel, thanks, but your solution proves that the email address is valid according to the specification, not whether or not the email address will ever be a valid email in production environments - since no-one will ever have this email address:
.............@t
. I'm not trying to validate it theoretically, but rather ensure that my users register with a valid email address. I've since decided that the only way to do that is to send out a confirmation email. -
hofnarwillie over 8 years@Cogwheel: All 36 of them? No.
-
hofnarwillie over 8 years@Cogwheel: if the answer lies somewhere in the comments it should probably be added to the main body of the answer.
-
Cogwheel over 8 years@hofnarwillie: it is in the main body, but the comments elaborate. If your goal is to not anger your users then your validation shouldn't be any more restrictive than the spec. The only way to truly verify whether an e-mail is valid is to send a test message.
-
hofnarwillie over 8 years@Cogwheel: That's a good idea. Thank you, I have now decided to send out a confirmation email.
-
B. Clay Shannon-B. Crow Raven over 8 yearsThis doesn't work for me; I get, "'Data Annotations' does not exist...are you missing an assembly reference?" Which reference do I need to add?
-
Joseph Ferris almost 8 years@RezaRahmati - That is correct. It is completely acceptable for an email address to resolve to a machine that is accessible on a local network, but not part of a domain. I have a test VM simply called "mail", and I can send to address@mail just fine, as I should. The gist of this approach is that if you are going to send via an SmptClient instance, you are going to use a MailAddress. This simply provides a means to proactively capture addresses that MailAddress would have eventually reject before sending. A large percentage (not all) of the comments here are actually addressed in the RFC.
-
ruffin over 7 years@ManicDee "Also read Mark Swanson, "How not to validate email" -- "Or maybe you will find a regular expression that looks something like
^[_a-z0-9-]+(\.[_a-z0-9-]omg-whyyyyy$
. ... So what should you do instead? Just check for the existence of @. Every email address will have at least one of them and it is trivially easy to write this code." The buttoned up coder in me is trying to resist, but the rest is surprisingly convincingly arguing that anything else is a sad tragedy of micro-optimization. -
Alexandru Dicu over 7 yearsThis is just horror :)
-
Illidan over 7 yearsSecurity remark: it is a well known DOS-like kind of attack, where a huge email expression provided to server, and it became busy forever while running email validation on that expression. Always check email string length BEFORE running 'IsEmailValid' method!
-
Stefan over 7 yearsI came up with the same regex ;) It does allow invalid charachters though
-
jao over 7 yearsThis will return true if source is null. See msdn.microsoft.com/en-us/library/hh192424 "true if the specified value is valid or null; otherwise, false."
-
NightWatchman about 7 yearsThis has the added benefit of working while targeting netstandard 1.6 which currently doesn't have access to System.Net.Mail
-
Chris about 7 yearsThis works, but don't forget
RegexOptions.IgnoreCase
because this pattern does not allow capital letters explicitly! -
Simone about 7 yearsThis answer doesn't accept an address with a TLD in the domain part.
-
Simone about 7 yearsThis answer does not accept a TLD in the domain part.
-
Simone about 7 yearsI'll keep your suggestion up to point 2. Way more future-proof than checking for a known domain name pattern.
-
Matthew Lock about 7 years@Simone probably nobody does have email addresses with the TLD in the domain part though in practice: serverfault.com/a/721929/167961 note in the comments it may be prohibited these days
-
Simone about 7 years@MatthewLock Could it be an intranet address? Like
bob@companyinternal
? -
Matthew Lock about 7 years@Simone does anyone in real life actually use that scheme?
-
Simone about 7 years@MatthewLock I don't know. Are you sure nobody does?
-
jimbobmcgee about 7 yearsNitpicking, but define "has a mail exchanger"? If no MX records exist, SMTP should fall back to the A/AAAA record, as per RFC2821/5321. If an MX record does exist, it still might not indicate a mail exchanger exists (RFC7505). Really, the only way is to send them a mail with a call-to-action link, and wait for them to reply...
-
urig about 7 yearsPlease note that
foo.IsValid(null);
returnstrue
. -
Deantwo almost 7 yearsAnd the maximum length of an email address is 254. See: stackoverflow.com/questions/386294/…
-
Ohad Schneider almost 7 years@Casey If you look at the reference source for the attribute (github.com/Microsoft/referencesource/blob/master/…), it says "This attribute provides server-side email validation equivalent to jquery validate, and therefore shares the same regular expression". So I suppose jQuery e-mail validation (I assume jqueryvalidation.org/email-method) is to blame.
-
Ohad Schneider almost 7 years@Aaroninus can you provide a specific example of an e-mail address this attribute rejects but
System.Net.Mail.MailAddress
accepts? -
Ohad Schneider almost 7 yearsThere's a trade-off here between protecting the user from a silly mistake (not realizing the field is an e-mail address, or making some typo) and the chance you user has some super-weird address that gets rejected by standard validators like
EmailAddressAttribute
andSystem.Net.Mail.MailAddress
. The way I see it, a person whose address is rejected by those is seriously screwed and my site is going to be the last of his troubles. Maybe a bank will see it otherwise. Of course if you want to go to the trouble of a coded link your answer is probably the best bet (without checking for.
even) -
Ohad Schneider almost 7 yearsNote that Regex is very deliberate: "This attribute provides server-side email validation equivalent to jquery validate, and therefore shares the same regular expression".
-
Ohad Schneider almost 7 yearsNice, but I only see paid editions. Any plans for a community/OpenSource edition?
-
Ohad Schneider almost 7 yearsOne more easy check worth adding is
3<=length<=254
(remembera@a
is valid) -
Efran Cobisi almost 7 years@OhadSchneider Yes: we are offering a free version of our email validation technology by way of Verifalia, our SaaS email verification service. Verifalia comes with free and open-source SDKs for the major software development platforms, including .NET.
-
Aaroninus almost 7 years@OhadSchneider An email address with only a TLD, e.g. example@com
-
Jan almost 7 years@ThomasAyoub I haven't seen an EmailAddressAttribute answer, and no answer that uses new MailAddress() with a check on input == .Address so I think its pretty useful. Without reading comments the accepted answer is pretty wrong. new MailAddress("Foobar [email protected]") proves that.
-
Bacon Bits almost 7 yearsHere's the actual source for EmailAddressAttribute. The regex and options can be found on lines 54 and 55.
-
AdamV over 6 yearsThis may seem like a good solution, the problem is it is expensive to catch exceptions. Run this side by side with a regex correctly implemented and you will see a difference. I had a similar issue with someone doing a try catch to determine if a string was null instead of just using string.IsNullOrWhitespace and the difference in performance is staggering.
-
youen over 6 years@AdamV my 2 cents : if you plan to check millions of e-mail addresses per second, then your comment is entirely valid. And I'm sure some people will actually want to do this. However, in most cases, this code will be used to check e-mails entered by a user on a website, and I believe even big websites will check only a few emails per second. Also, the purpose of an e-mail address is to send e-mails, which is probably 1 million times slower than throwing an exception. Bottom line is: don't optimize prematurely, unless the (supposedly) faster code is as simple, not error-prone, and maintainable.
-
Ray Cheng over 6 yearsIt'll fail to validate [email protected] as a valid email address.
-
Guney Ozsan over 6 yearsIf using .NET 2.0 any non empty string returns true. I didn't test other versions. Why 2.0? Because Unity 3D.
-
Cogwheel over 6 years@GuneyOzsan It's not 2.0's fault it's Unity's. Unity's C# environment is very different from actual .Net
-
Guney Ozsan over 6 years@Cogwheel Thanks for the clarification. I didn't think it was a fault but I thought maybe earlier .Net was extremely more flexible about email address conditions. Unfortunately the unexpected cases of Unity can make such specialized things pretty hard time to time. Perhaps we should better call it C#-Unity.
-
gdbj over 6 yearsWhat's nice about this approach is we don't need another library reference, ie
System.Net.Mail
-
ruffin over 6 years@Jan fwiw, Manik beat Knickerless to the
EmailAddressAttribute
by just under four months, though this one does catch thenull
issue. -
Sebastian Hofmann over 6 yearsA better version:
public static Boolean IsValidMailAddress(this String pThis) => pThis == null ? false : new EmailAddressAttribute().IsValid(pThis);
-
Patrik Melander about 6 yearsOr even better:
public static bool IsValidEmailAddress(this string address) => address != null && new EmailAddressAttribute().IsValid(address);
-
Bat_Programmer almost 6 yearsThanks this is the best solution and should be accepted answer.
-
Langdon almost 6 yearsThis doesn't seem to help...
Console.WriteLine(MailAddress("asdf@asdf.").Address);
outputs "asdf@asdf.", which is not valid. -
rethabile almost 6 years.net seems to have its own definition of valid. related discussion
-
Jon49 over 5 yearsOr even better better:
public static bool IsValidEmailAddress(this string address) => !(address is null) && new EmailAddressAttribute().IsValid(address);
:-) -
Marco de Zeeuw about 5 yearsThe risk of this is that you are validating a different e-mailaddress than the source, leaving you to think you can mail to the (in this case) untrimmed version of the specified e-mailaddress. A better approach would be to make a seperate method
SanitizeEmail(string email)
, using the result of that method to validate and send the email to. -
VDWWD about 5 yearsI use this method too. But i've put
if (string.IsNullOrEmpty(email) || email.Contains("@-") || email.Trim().Contains(" ")) return false;
above the try-catch. Because as far as I know an email address cannot contain a space or a dash right after the @. ButMailAddress
will return them true. SeeIsValidEmail("[email protected]") > true
andIsValidEmail("fake@fal se.com") > false
andIsValidEmail("fa [email protected]") > true
-
Goner Doug about 5 yearsI had to change public static bool IsValidEmail(this string email) to public static bool IsValidEmail(string email) to avoid THIS: stackoverflow.com/questions/10412233/…
-
Naveen about 5 years@Goner Doug, this functionlity will work like this.(bool flag = EmailAddress.IsValidEmail())
-
Goner Doug about 5 yearsthe "THIS" needed to be removed to avoid causing compiler issues when added to my form.
-
Cogwheel about 5 years@VDWWD The address portion can be quoted which means
@-
and space could appear in a valid address -
Marc.2377 about 5 yearsI don't think this extension method should silently return
false
for null strings. That's why I propose the (even better better)++ version:public static bool IsValidEmailAddress(this string address) => new EmailAddressAttribute().IsValid(address ?? throw new ArgumentNullException());
. I'll now go and found the Reformed Church of the Even Better Better Versionists. -
Naveen almost 5 years@Goner Doug, Its functionlity will work like this. string email = "[email protected]"; if (email.IsValidEmail()){ return false; }else { return true;}
-
Student222 almost 5 yearsSource code here github.com/microsoft/referencesource/blob/master/… It uses Regex internally. And uses the same Regex as jquery
-
Admin almost 5 yearsthe method name is not using proper conventions. The method body could be clearer
-
Bilgin Kılıç over 4 yearsaaa [email protected] is not valid but this is not working.
-
Guy Cohen over 4 yearsIMHO it is not valid, try "[email protected]"
-
Govinda Rajbhar over 4 yearsfor me this line returning true which is not correct
var result = new EmailAddressAttribute().IsValid("govinda@gmailcom");
-
Govinda Rajbhar over 4 yearsThis code is also returning true for me which is not correct.
var addr = new System.Net.Mail.MailAddress("govinda@gmailcom"); return addr.Address == email;
-
SendETHToThisAddress about 4 yearsThanks I like the 1 liner solution, I used it in a method I added in my data validation class. 1 improvement I would suggest for your answer is changing the variables name "foo" to "emailTester" and "bar" to "valid", or similar variable names that are more descriptive.
-
Cogwheel almost 4 years@GovindaRajbhar that is a valid email address. See the examples in the answer and the comments above.
-
Hoffs over 3 yearsAlso note that .Net Core implementation seems to be wildly different and way simpler than .Net Framework one: source.dot.net/#System.ComponentModel.Annotations/System/…
-
Владимiръ over 3 yearsthis will not validate emails with 1 character domain. i.e: [email protected]
-
David Silva Smith over 3 years@Владимiръ did you run the code? Last time someone said it didn't work, I fired up a coding environment and it did validate properly. I haven't used C# in about 8 years and I'm genuinely curious if you know it doesn't work or if you are reading the code and saying it doesn't work.
-
Mario Favere about 3 yearsThis code returns a false positive on e.g. 'myusername@gmail?com'
-
David Jones almost 3 yearsHeuristic Checks. I first checked for null, then trimmed and nullorempty check, then checked for one and only one @ then at least one period then finally length of string >3 . Fail on these returns false. Otherwise use the code above. This cleaned up getting some null error messages although trapped.
-
TK-421 almost 3 yearsThis method shows that "[email protected]." is a valid email. Emails can't end with a dot.
-
Eranga Gamagedara almost 3 yearsThis is not a good way to validate the email. This is what is inside this method, ` public override bool IsValid(object value) { if (value == null) { return true; } if (!(value is string valueAsString))return false; int index = valueAsString.IndexOf('@'); return index > 0 && index != valueAsString.Length - 1 && index == valueAsString.LastIndexOf('@'); }`
-
Cogwheel almost 3 years@TK-421 that is incorrect. All DNS addresses end with an implicit
.
.test.com.
is identical totest.com
. Try it in your browser. -
TK-421 almost 3 yearsIt might work in a browser, but it doesn't work as an email address.
-
Cogwheel almost 3 years@TK-421 that's a problem with the email client, not the format of the email. Everything after @ is just a domain name.
-
iRubens almost 3 yearsAs pointed out by @Hoffs the current implementation it's very different. Now only checks for the "@" character! Really scarily a text like "[email protected]' or 1=1" now is considered valid. I think a very visible disclaimer for NetCore implementations needs to be added...
-
Cogwheel almost 3 years@TK-421: I stand corrected. The RFC that describes mail addresses does not refer to the DNS specification. It has its own definition of the domain part of the address and does not seem to allow for a period.
-
Mike Weiss over 2 yearsThis won't work if the email argument ends in a space but is otherwise valid. On the comparison line in the Try block it will fail because one ends in a space and the other does not. Need to also Trim() the email in the comparison for a fix.
-
Muleskinner over 2 years@GovindaRajbhar govinda@gmailcom is a perfectly valid email address.
-
deanwilliammills over 2 years"this is not valid@email$com" return True....
-
Chad Grant over 2 yearswhy do people insist on being lazy and using exceptions for control flow?
-
Erçin Dedeoğlu over 2 yearsdid you ask this question yourself? why you are here :)
-
Premier Bromanov about 2 yearsWorks for detecting multiple
.
in a row and,
outside of quotes, and seems to follow standards listed here: en.wikipedia.org/wiki/Email_address#Local-part but does not allow for international characters permitted by RFC 6530. -
CodeMan03 about 2 yearsa+b@b comes as valid using this code but that is not a valid email