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

How to Elegantly Validate Email Addresses in C#?

DDD
DDDOriginal
2025-01-21 09:46:08767browse

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:

  • cog@wheel
  • "cogwheel the orange"@example.com
  • 123@$.xyz

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!

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