Home >Backend Development >C++ >How to Reliably Validate Email Addresses in C#?

How to Reliably Validate Email Addresses in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-21 09:42:10575browse

How to Reliably Validate Email Addresses in C#?

Reliable email address verification method 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:

  • Space at the end of the email address.
  • A valid email address format when parsed using MailAddress.
  • Match between original email address and parsed address to avoid false positives.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn