Reputation: 475
I'm using MailAddress
to attempt to validate a given email.
I get a valid email when I give it a string like "someName@gmail".
I was expecting it to fail with a FormatException
since the email is missing .com at the end. Why is it not failing to parse the email here?
public bool IsEmailValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Upvotes: 2
Views: 187
Reputation: 3062
someName@gmail
is actually a perfectly valid email address, in that it conforms to the email format specification (formally IETF RFC2822). However it is almost certainly not routable unless you happen to have a mail server on your local network with the DNS name gmail
.
If you would like to check for this particular problem, I would suggest adding a second check that there is a dot after the @
symbol.
EDIT: Please note that this is a business decision that you have to make. By invalidating email addresses with a .
after the @
, you are breaking the standard email specification, however I feel that in perhaps 99.99% of cases dealing with external mail this is an acceptable tradeoff to make to prevent users mistakenly typing myname@hotmail
or myname@gmail
(I'd wager a common mistake among new Internet users).
This could conceivably block legitimate external email, say if I owned the TLD tt
I could have a legitimate email address bob@tt
, and mail handling systems like yours should handle my address without complaining. However as it has been noted in this answer, this is very uncommon.
Having said that, here's some code that would achieve this:
public bool IsEmailValid(string emailaddress){
if (emailaddress == null || !emailaddress.Contains("@") || !emailaddress.Split("@")[1].Contains("."))
{
return false; // Doesn't contain "@" or doesn't contain a "." after the "@"
}
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Unless you have a very limited range of possible email addresses, don't go trying to limit top level domains. For example only allowing .com
, .net
and .org
would be a big mistake - as of writing there are over 1500 TLDs which an email address could conceivably end in
Upvotes: 2
Reputation: 6659
x@host
is a legally formatted email address. The MailAddress
class only looks at the format of the string, not the validity of the address. You'll have to resolve the host name, send an email to the recipient and wait for the absence of a bounce mail or the presence of a return receipt to fully validate the address.
Upvotes: 3