Reputation: 422
what would you recommend to get a simple result like "IsMailValid?" -> true|false?
Since speed is not that relevant, i think going the way with MailAddressParser would be OK?
Regards
John
Upvotes: 1
Views: 607
Reputation: 73574
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.
Upvotes: 1
Reputation: 6111
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
Upvotes: 0