Home >Backend Development >C++ >How to Elegantly Validate Email Addresses in C#?
Elegant email address verification method in C#
Looking for efficient email address verification codes? The following solutions are both elegant and efficient:
<code class="language-csharp">bool IsValidEmail(string email) { string trimmedEmail = email.Trim(); if (trimmedEmail.EndsWith(".")) { return false; // @TK-421建议 } try { var addr = new System.Net.Mail.MailAddress(email); return addr.Address == trimmedEmail; } catch { return false; } }</code>
Resolving potential issues
As Stuart pointed out, the original implementation returned false positive results due to the presence of spaces in the email address. This problem was solved by comparing the parsed address with the original string.
Instructions for email verification
It should be noted that this verification checks the syntax of the email address and does not guarantee its functionality. To verify actual deliverability, mail delivery is the only sure way to test.
Identifies valid email variants
Contrary to common assumption, email addresses exhibit flexibility in their syntax. Valid forms include:
Therefore, false positives are preferable to false negatives in most applications.
Explore further
For more insights and alternatives, please refer to the following resources:
The above is the detailed content of How to Elegantly Validate Email Addresses in C#?. For more information, please follow other related articles on the PHP Chinese website!