Reputation: 3817
I have read on SO about validating emails with MailAddress and have produced the folowing code:
try
{
var address = new MailAddress(value.Email);
}
catch (FormatException)
{
emailError = "Invalid Email";
}
To my great surprise, the string ndskfndlfk@sdflsdf
validates as good email.
Any idea why is it so?
Upvotes: 2
Views: 2710
Reputation: 45096
That might not be valid WWW domain name but on a private network I think it is a valid domain name. If you want to get more selective then Regex.
I try and parse legit email (eliminate phony used by spam) using Regex and it is messy.
If you have access to the actual email header then it does not really get easier but it get more accurate.
Upvotes: 1
Reputation: 2392
If you really need to filter those email addresses, you could use the little utility found here, which uses Regex to validate email addresses. Note that this is the .Net 4.0 version - it's a little different for 4.5.
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public class RegexUtilities
{
bool invalid = false;
public bool IsValidEmail(string strIn)
{
invalid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
if (invalid)
return false;
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn,
@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.IgnoreCase);
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try {
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException) {
invalid = true;
}
return match.Groups[1].Value + domainName;
}
}
Otherwise, if it's for user registration, I usually just depend on email verification - i.e. the system sends the user an email with a link, and clicking the link therefore validates that the email address is real.
It is possible for a valid email address not to be a real one. In other words, it may even pass a perfect validation system, but that's no guarantee that it exists.
Upvotes: 1