Reputation: 48516
In reading about what would be the best way to validate a mail address via regular expressions, I came across with an attempt to validate with
try
{
new MailAddress(input);
}
catch (Exception ex)
{
// invalid
}
What method does the MailAddress
class use to ensure a mail address is valid?
Upvotes: 2
Views: 4614
Reputation: 2343
You can see the source code without using Reflector using the new .NET Reference Source. Here's the link to the MailAddress class.
Upvotes: 6
Reputation: 69270
According to the documentation
The address parameter can contain a display name and the associated e-mail address if you enclose the address in angle brackets. For example:
"Tom Smith <[email protected]>"
White space is permitted between the display name and the angle brackets.
So a "naked" address such as [email protected] or one with a displayed name as mentioned in the documentation is fine. It is impossible to tell how the validation is done internally without access to the code, but a regex doing that validation can of course be constructed.
Upvotes: 0
Reputation: 28530
If you mean by validate whether or not it's a valid e-mail address format, it supports several standard formats:
The MailAddress class supports the following mail address formats:
A simple address format of user@host. If a DisplayName is not set, this is the mail address format generated.
A standard quoted display name format of "display name" . If a DisplayName is set, this is the format generated.
Angle brackets are added around the User name, Host name for "display name" user@host if these are not included.
Quotes are added around the DisplayName for display name , if these are not included.
Unicode characters are supported in the DisplayName. property.
A User name with quotes. For example, "user name"@host.
Consecutive and trailing dots in user names. For example, user...name..@host.
Bracketed domain literals. For example, .
Comments. For example, (comment)"display name"(comment)<(comment)user(comment)@(comment)domain(comment)>(comment). Comments are removed before transmission
.
This is from MailAddress Class
As for what method it uses to validate the formats, I don't know. You could always try Reflector to see what it's doing internally. Is there a particular reason you want to know the internal details?
Upvotes: 2