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:17

The most elegant way is to use .Net's built in methods.

These methods:

  • Are tried and tested. These methods are used in my own professional projects.

  • Use regular expressions internally, which are reliable and fast.

  • Made by Microsoft for C#. There's no need to reinvent the wheel.

  • Return a bool result. True means the email is valid.

For users of .Net 4.5 and greater

Add this Reference to your project:

System.ComponentModel.DataAnnotations

Now you can use the following code:

(new EmailAddressAttribute().IsValid("youremailhere@test.test"));

Example of use

Here are some methods to declare:

protected List<string> GetRecipients() // Gets recipients from TextBox named `TxtRecipients`
{
    List<string> MethodResult = null;

    try
    {
        List<string> Recipients = TxtRecipients.Text.Replace(",",";").Replace(" ", "").Split(';').ToList();

        List<string> RecipientsCleaned = new List<string>();

        foreach (string Recipient in RecipientsCleaned)
        {
            if (!String.IsNullOrWhiteSpace(Recipient))
            {
                RecipientsNoBlanks.Add(Recipient);

            }

        }

        MethodResult = RecipientsNoBlanks;

    }
    catch//(Exception ex)
    {
        //ex.HandleException();
    }

    return MethodResult;

}


public static bool IsValidEmailAddresses(List<string> recipients)
{
    List<string> InvalidAddresses = GetInvalidEmailAddresses(recipients);

    return InvalidAddresses != null && InvalidAddresses.Count == 0;

}

public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
    List<string> MethodResult = null;

    try
    {
        List<string> InvalidEmailAddresses = new List<string>();

        foreach (string Recipient in recipients)
        {
            if (!(new EmailAddressAttribute().IsValid(Recipient)) && !InvalidEmailAddresses.Contains(Recipient))
            {
                InvalidEmailAddresses.Add(Recipient);

            }

        }

        MethodResult = InvalidEmailAddresses;

    }
    catch//(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

...and code demonstrating them in action:

List<string> Recipients = GetRecipients();

bool IsValidEmailAddresses = IsValidEmailAddresses(Recipients);

if (IsValidEmailAddresses)
{
    //Emails are valid. Your code here

}
else
{
    StringBuilder sb = new StringBuilder();

    sb.Append("The following addresses are invalid:");

    List<string> InvalidEmails = GetInvalidEmailAddresses(Recipients);

    foreach (string InvalidEmail in InvalidEmails)
    {
        sb.Append("\n" + InvalidEmail);

    }

    MessageBox.Show(sb.ToString());

}

In addition, this example:

  • Extends beyond the spec since a single string is used to contain 0, one or many email addresses sperated by a semi-colon ;.
  • Clearly demonstrates how to use the IsValid method of the EmailAddressAttribute object.

Alternative, for users of a version of .Net less than 4.5

For situations where .Net 4.5 is not available, I use the following solution:

Specifically, I use:

public static bool IsValidEmailAddress(string emailAddress)
{
    bool MethodResult = false;

    try
    {
        MailAddress m = new MailAddress(emailAddress);

        MethodResult = m.Address == emailAddress;

    }
    catch //(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
    List<string> MethodResult = null;

    try
    {
        List<string> InvalidEmailAddresses = new List<string>();

        foreach (string Recipient in recipients)
        {
            if (!IsValidEmail(Recipient) && !InvalidEmailAddresses.Contains(Recipient))
            {
                InvalidEmailAddresses.Add(Recipient);

            }

        }

        MethodResult = InvalidEmailAddresses;

    }
    catch //(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}
查看更多
其实,你不懂
3楼-- · 2019-01-01 05:18

I wrote an function to check if an email is valid or not. It seems working well for me in most cases.

Results:

dasddas-@.com => FALSE
-asd@das.com => FALSE
as3d@dac.coas- => FALSE
dsq!a?@das.com => FALSE
_dasd@sd.com => FALSE
dad@sds => FALSE
asd-@asd.com => FALSE
dasd_-@jdas.com => FALSE
asd@dasd@asd.cm => FALSE
da23@das..com => FALSE
_dasd_das_@9.com => FALSE

d23d@da9.co9 => TRUE
dasd.dadas@dasd.com => TRUE
dda_das@das-dasd.com => TRUE
dasd-dasd@das.com.das => TRUE

Code:

    private bool IsValidEmail(string email)
    {
        bool valid = false;
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            valid = true;
        }
        catch
        {
            valid = false;
            goto End_Func;
        }

        valid = false;
        int pos_at = email.IndexOf('@');
        char checker = Convert.ToChar(email.Substring(pos_at + 1, 1));
        var chars = "qwertyuiopasdfghjklzxcvbnm0123456789";
        foreach (char chr in chars)
        {
            if (checker == chr)
            {
                valid = true;
                break;
            }
        }
        if (valid == false)
        {
            goto End_Func;
        } 

        int pos_dot = email.IndexOf('.', pos_at + 1);
        if(pos_dot == -1)
        {
            valid = false;
            goto End_Func;
        }

        valid = false;
        try
        {
            checker = Convert.ToChar(email.Substring(pos_dot + 1, 1));
            foreach (char chr in chars)
            {
                if (checker == chr)
                {
                    valid = true;
                    break;
                }
            }
        }
        catch
        {
            valid = false;
            goto End_Func;
        }

        Regex valid_checker = new Regex(@"^[a-zA-Z0-9_@.-]*$");
        valid = valid_checker.IsMatch(email);
        if (valid == false)
        {
            goto End_Func;
        }

        List<int> pos_list = new List<int> { };
        int pos = 0;
        while (email.IndexOf('_', pos) != -1)
        {
            pos_list.Add(email.IndexOf('_', pos));
            pos = email.IndexOf('_', pos) + 1;
        }

        pos = 0;
        while (email.IndexOf('.', pos) != -1)
        {
            pos_list.Add(email.IndexOf('.', pos));
            pos = email.IndexOf('.', pos) + 1;
        }

        pos = 0;
        while (email.IndexOf('-', pos) != -1)
        {
            pos_list.Add(email.IndexOf('-', pos));
            pos = email.IndexOf('-', pos) + 1;
        }

        int sp_cnt = pos_list.Count();
        pos_list.Sort();
        for (int i = 0; i < sp_cnt - 1; i++)
        {
            if (pos_list[i] + 1 == pos_list[i + 1])
            {
                valid = false;
                break;
            }

            if (pos_list[i]+1 == pos_at || pos_list[i]+1 == pos_dot)
            {
                valid = false;
                break;
            }
        }

        if(valid == false)
        {
            goto End_Func;
        }

        if (pos_list[sp_cnt - 1] == email.Length - 1 || pos_list[0] == 0)
        {
            valid = false;
        }

    End_Func:;
        return valid;
    }
查看更多
梦寄多情
4楼-- · 2019-01-01 05:19

a little modification to @Cogwheel answer

public static bool IsValidEmail(this string email)
{
  // skip the exception & return early if possible
  if (email.IndexOf("@") <= 0) return false;

  try
  {
    var address = new MailAddress(email);
    return address.Address == email;
  }
  catch
  {
    return false;
  }
}
查看更多
ら面具成の殇う
5楼-- · 2019-01-01 05:20

Here is an answer to your question for you to check.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class RegexUtilities
{    
   public bool IsValidEmail(string strIn)
   {
       if (String.IsNullOrEmpty(strIn))
       {
          return false;

       }

       // Use IdnMapping class to convert Unicode domain names.

       try 
       {
          strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));

       }
       catch (RegexMatchTimeoutException) 
       {
           return false;

       }

       if (invalid)
       {
           return false;

       }

       // Return true if strIn is in valid e-mail format.    

       try 
       {
          return Regex.IsMatch(strIn, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|       [-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));

       }
       catch (RegexMatchTimeoutException) 
       {
          return false;

       }

   }


   private string DomainMapper(Match match)
   {
      // IdnMapping class with default property values.

      IdnMapping idn = new IdnMapping();

      string domainName = match.Groups[2].Value;

      try 
      {
         domainName = idn.GetAscii(domainName);

      }
      catch (ArgumentException) 
      {
         invalid = true;

      }

      return match.Groups[1].Value + domainName;

   }

}
查看更多
时光乱了年华
6楼-- · 2019-01-01 05:21

What about this?

bool IsValidEmail(string email)
{
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch {
        return false;
    }
}

To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.

Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:

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

For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.

Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow

查看更多
骚的不知所云
7楼-- · 2019-01-01 05:21

In case you are using FluentValidation you could write something as simple as this:

public cass User
{
    public string Email { get; set; }
}

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(x => x.Email).EmailAddress().WithMessage("The text entered is not a valid email address.");
    }
}

// Validates an user. 
var validationResult = new UserValidator().Validate(new User { Email = "açflkdj" });

// This will return false, since the user email is not valid.
bool userIsValid = validationResult.IsValid;
查看更多
登录 后发表回答