true|false? is it save to 开发者_运维知识库use a regExp" />
开发者

.NET: Email Address Parsing - save with RegExp or just Try/Catch around Mail.MailAddressParser?

what would you recommend to get a simple result like "IsMailValid?" -> true|false?

  • is it save to 开发者_运维知识库use a regExp
  • is it better to use .NET's System...Mail.MailAddressParser with a simple try/catch around it?

Since speed is not that relevant, i think going the way with MailAddressParser would be OK?

Regards

John


Given your requirements specifically speed not being necessary, I would use the Mail.MailAddressParser with a try/catch. It's guaranteed to filter out anything the .NET runtime can't recognize as a valid email address, and its much simpler.

A good regex will likely do the same, but a bad regex will give you false positives, false negatives, or both.

The performance cost in handling exceptions would make me go the other way if speed were a factor, but in this case, with your requirements, less code, more readable code, and it "just works" all balance out the performance factor.

Clarification:

I'm assuming your intended code would look like this:

try
{
   System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(somestring);
}
catch(Exception ex)
{
   // handle invalid email addresses here.
}

And my recommendation is only for this situation. This is an intentional exception to the best practices of not using Exceptions where other methods would work and only suggested because of the explicit statement that performance is not a factor.


It is against .NET Best Practices to use exceptions where you expect failures on a regular basis. The reason is exceptions are very expensive.

I would use a Regular Expression in compiled mode to filter out the bad email addresses.

Something like this would work perfectly:

Private Function ValidEmail(ByVal Email As String) As Boolean
    If Text.RegularExpressions.Regex.IsMatch(Trim(Email), "^\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b$", RegexOptions.IgnoreCase Or RegexOptions.Compiled) = False Then
        Return False
    Else
        Return True
    End If
End Function
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜