开发者

How does the MailAddress constructor validate mail addresses

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 cla开发者_JAVA技巧ss use to ensure a mail address is valid?


You can see the source code without using Reflector using the new .NET Reference Source. Here's the link to the MailAddress class.


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?


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 <tsmith@contoso.com>"

White space is permitted between the display name and the angle brackets.

So a "naked" address such as tsmith@contos.com 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜