Home >Backend Development >C++ >How to Reliably Validate Email Addresses in C#?
Email address verification ensures it conforms to a specific format and can receive emails. In C#, the most elegant solution is to utilize the System.Net.Mail.MailAddress class:
<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>
This code checks various conditions:
It is important to note that email addresses may have unconventional forms, for example:
<code>cog@wheel "cogwheel the orange"@example.com 123@$.xyz</code>
These are all valid email addresses, so it’s crucial to avoid false “invalid” results that can impact the user experience.
Exception handling is generally not recommended for business logic, but in this case it makes the code clearer and more concise. Additionally, it allows specific error handling, such as catching exceptions related to null, empty, or invalid formats.
The above is the detailed content of How to Reliably Validate Email Addresses in C#?. For more information, please follow other related articles on the PHP Chinese website!