C# code to validate email address

2019-01-01 04:25发布

What is the most elegant code to validate that a string is a valid email address?

30条回答
浅入江南
2楼-- · 2019-01-01 05:06

There are a lot of strong answers here. However, I recommend that we take a step back. @Cogwheel answers the question https://stackoverflow.com/a/1374644/388267. Nevertheless, it could be costly in a bulk validation scenario, if many of the email address being validated are invalid. I suggest that we employ a bit of logic before we enter into his try-catch block. I know that the following code could be written using RegEx but that could be costly for new developers to understand. This is my twopence worth:

    public static bool IsEmail(this string input)
    {
        if (string.IsNullOrWhiteSpace(input)) return false;

        // MUST CONTAIN ONE AND ONLY ONE @
        var atCount = input.Count(c => c == '@');
        if (atCount != 1) return false;

        // MUST CONTAIN PERIOD
        if (!input.Contains(".")) return false;

        // @ MUST OCCUR BEFORE LAST PERIOD
        var indexOfAt = input.IndexOf("@", StringComparison.Ordinal);
        var lastIndexOfPeriod = input.LastIndexOf(".", StringComparison.Ordinal);
        var atBeforeLastPeriod = lastIndexOfPeriod > indexOfAt;
        if (!atBeforeLastPeriod) return false;

        // CODE FROM COGWHEEL'S ANSWER: https://stackoverflow.com/a/1374644/388267 
        try
        {
            var addr = new System.Net.Mail.MailAddress(input);
            return addr.Address == input;
        }
        catch
        {
            return false;
        }
    }
查看更多
高级女魔头
3楼-- · 2019-01-01 05:07

I use this single liner method which does the work for me-

using System.ComponentModel.DataAnnotations;
public bool IsValidEmail(string source)
{
    return new EmailAddressAttribute().IsValid(source);
}

As per the comments, this will "fail" if the source (the email address) is null.

public static bool IsValidEmailAddress(this string address) => address != null && new EmailAddressAttribute().IsValid(address);
查看更多
栀子花@的思念
4楼-- · 2019-01-01 05:07

I find this regex to be a good trade off between checking for something more than just the @ mark, and accepting weird edge cases:

^[^@\s]+@[^@\s]+(\.[^@\s]+)+$

It will at least make you put something around the @ mark, and put at least a normal looking domain.

查看更多
一个人的天荒地老
5楼-- · 2019-01-01 05:09

The most voted answer from @Cogwheel is best answer however i have tried to implement trim() string method so it will trim all user white space from string start to end. Check the code bellow for full example-

bool IsValidEmail(string email)
{
    try
    {
        email = email.Trim();
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch
    {
        return false;
    }
}
查看更多
旧人旧事旧时光
6楼-- · 2019-01-01 05:09

Simple way to identify the emailid is valid or not.

public static bool EmailIsValid(string email)
{
        return Regex.IsMatch(email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
查看更多
梦醉为红颜
7楼-- · 2019-01-01 05:11

There is culture problem in regex in C# rather then js. So we need to use regex in US mode for email check. If you don't use ECMAScript mode, your language special characters are imply in A-Z with regex.

Regex.IsMatch(email, @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9_\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.ECMAScript)
查看更多
登录 后发表回答