Home >Backend Development >C++ >How Can I Robustly Validate Email Addresses in C#?
When dealing with email addresses, it is crucial to verify their validity to ensure smooth communication. This code snippet provides a powerful email address verification solution:
<code class="language-csharp">bool IsValidEmail(string email) { var 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>
This code goes beyond basic syntax checking by leveraging the MailAddress class in the System.Net.Mail namespace. It parses the input string into a MailAddress object. If the parsing is successful, it compares the generated address to the original string to ensure that no extra spaces or special characters were introduced during the parsing process.
Other considerations
Exception handling
This code utilizes exception handling to simplify business logic. If any error occurs during MailAddress initialization, it is logically converted to an invalid email address without complex condition checks.
More resources
The above is the detailed content of How Can I Robustly Validate Email Addresses in C#?. For more information, please follow other related articles on the PHP Chinese website!