Regex Email validation

后端 未结 30 894
北海茫月
北海茫月 2020-11-22 12:16

I use this

@\"^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$\"

regexp to validate the email

([\\w\\.\\-]+) - this is f

相关标签:
30条回答
  • 2020-11-22 12:21

    Why not use EF6 attribute based e-mail validation?

    As you can see above, Regex validation for e-mail always has some hole in it. If you are using EF6 data annotations, you can easily achieve reliable and stronger e-mail validation with EmailAddress data annotation attribute available for that. I had to remove the regex validation I used before for e-mail when I got mobile device specific regex failure on e-mail input field. When the data annotation attribute used for e-mail validation, the issue on mobile was resolved.

    public class LoginViewModel
    {
        [EmailAddress(ErrorMessage = "The email format is not valid")]
        public string Email{ get; set; }
    
    0 讨论(0)
  • 2020-11-22 12:21

    This one prevents invalid emails mentioned by others in the comments:

    Abc.@example.com
    Abc..123@example.com
    name@hotmail
    toms.email.@gmail.com
    test@-online.com
    

    It also prevents emails with double dots:

    hello..world@example..com
    

    Try testing it with as many invalid email addresses as you can find.

    using System.Text.RegularExpressions;
    
    public static bool IsValidEmail(string email)
    {
        return Regex.IsMatch(email, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
            && Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
    }
    

    See validate email address using regular expression in C#.

    0 讨论(0)
  • 2020-11-22 12:22

    1

    ^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$
    

    2

    ^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$
    
    0 讨论(0)
  • Regex Email Pattern:

    ^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$
    
    0 讨论(0)
  • 2020-11-22 12:23

    It has taken many attempts to create an email validator which catches nearly all worldwide requirements for email.

    Extension method you can call with:

    myEmailString.IsValidEmailAddress();
    

    Regex pattern string you can get by calling:

    var myPattern = Regex.EmailPattern;
    

    The Code (mostly comments):

        /// <summary>
        /// Validates the string is an Email Address...
        /// </summary>
        /// <param name="emailAddress"></param>
        /// <returns>bool</returns>
        public static bool IsValidEmailAddress(this string emailAddress)
        {
            var valid = true;
            var isnotblank = false;
    
            var email = emailAddress.Trim();
            if (email.Length > 0)
            {
                // Email Address Cannot start with period.
                // Name portion must be at least one character
                // In the Name, valid characters are:  a-z 0-9 ! # _ % & ' " = ` { } ~ - + * ? ^ | / $
                // Cannot have period immediately before @ sign.
                // Cannot have two @ symbols
                // In the domain, valid characters are: a-z 0-9 - .
                // Domain cannot start with a period or dash
                // Domain name must be 2 characters.. not more than 256 characters
                // Domain cannot end with a period or dash.
                // Domain must contain a period
                isnotblank = true;
                valid = Regex.IsMatch(email, Regex.EmailPattern, RegexOptions.IgnoreCase) &&
                    !email.StartsWith("-") &&
                    !email.StartsWith(".") &&
                    !email.EndsWith(".") && 
                    !email.Contains("..") &&
                    !email.Contains(".@") &&
                    !email.Contains("@.");
            }
    
            return (valid && isnotblank);
        }
    
        /// <summary>
        /// Validates the string is an Email Address or a delimited string of email addresses...
        /// </summary>
        /// <param name="emailAddress"></param>
        /// <returns>bool</returns>
        public static bool IsValidEmailAddressDelimitedList(this string emailAddress, char delimiter = ';')
        {
            var valid = true;
            var isnotblank = false;
    
            string[] emails = emailAddress.Split(delimiter);
    
            foreach (string e in emails)
            {
                var email = e.Trim();
                if (email.Length > 0 && valid) // if valid == false, no reason to continue checking
                {
                    isnotblank = true;
                    if (!email.IsValidEmailAddress())
                    {
                        valid = false;
                    }
                }
            }
            return (valid && isnotblank);
        }
    
        public class Regex
        {
            /// <summary>
            /// Set of Unicode Characters currently supported in the application for email, etc.
            /// </summary>
            public static readonly string UnicodeCharacters = "À-ÿ\p{L}\p{M}ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß"; // German and French
    
            /// <summary>
            /// Set of Symbol Characters currently supported in the application for email, etc.
            /// Needed if a client side validator is being used.
            /// Not needed if validation is done server side.
            /// The difference is due to subtle differences in Regex engines.
            /// </summary>
            public static readonly string SymbolCharacters = @"!#%&'""=`{}~\.\-\+\*\?\^\|\/\$";
    
            /// <summary>
            /// Regular Expression string pattern used to match an email address.
            /// The following characters will be supported anywhere in the email address:
            /// ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß[a - z][A - Z][0 - 9] _
            /// The following symbols will be supported in the first part of the email address(before the @ symbol):
            /// !#%&'"=`{}~.-+*?^|\/$
            /// Emails cannot start or end with periods,dashes or @.
            /// Emails cannot have two @ symbols.
            /// Emails must have an @ symbol followed later by a period.
            /// Emails cannot have a period before or after the @ symbol.
            /// </summary>
            public static readonly string EmailPattern = String.Format(
                @"^([\w{0}{2}])+@{1}[\w{0}]+([-.][\w{0}]+)*\.[\w{0}]+([-.][\w{0}]+)*$",                     //  @"^[{0}\w]+([-+.'][{0}\w]+)*@[{0}\w]+([-.][{0}\w]+)*\.[{0}\w]+([-.][{0}\w]+)*$",
                UnicodeCharacters,
                "{1}",
                SymbolCharacters
            );
        }
    
    0 讨论(0)
  • 2020-11-22 12:24

    Just let me know IF it doesn't work :)

    public static bool isValidEmail(this string email)
    {
    
        string[] mail = email.Split(new string[] { "@" }, StringSplitOptions.None);
    
        if (mail.Length != 2)
            return false;
    
        //check part before ...@
    
        if (mail[0].Length < 1)
            return false;
    
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-\.]+$");
        if (!regex.IsMatch(mail[0]))
            return false;
    
        //check part after @...
    
        string[] domain = mail[1].Split(new string[] { "." }, StringSplitOptions.None);
    
        if (domain.Length < 2)
            return false;
    
        regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-]+$");
    
        foreach (string d in domain)
        {
            if (!regex.IsMatch(d))
                return false;
        }
    
        //get TLD
        if (domain[domain.Length - 1].Length < 2)
            return false;
    
        return true;
    
    }
    
    0 讨论(0)
提交回复
热议问题