简体   繁体   English

正则表达式不验证域名

[英]Regular expression not validating domain name

I have this utility function as follows: 我具有以下实用程序功能:

   public bool IsValidDomainName(string strIn)
        {
            return Regex.IsMatch(strIn, @"^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$");
        }

This expression works using modelbinding validation in MVC: 该表达式在MVC中使用模型绑定验证起作用:

[RegularExpression(@"^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$", ErrorMessage = "Please enter valid website address")]

So my question is why is my utility function failing? 所以我的问题是为什么我的效用函数会失败?

Update: 更新:

 public class RegexUtilities
    {
        bool invalid;

        public bool IsValidEmail(string strIn)
        {
            invalid = false;
            if (String.IsNullOrEmpty(strIn))
                return false;

            // Use IdnMapping class to convert Unicode domain names.
            strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper);
            if (invalid)
                return false;

            // Return true if strIn is in valid e-mail format.
            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]{2,17}))$",
                                 RegexOptions.IgnoreCase);
        }

        public bool IsValidDomainName(string strIn)
        {
            return Regex.IsMatch(strIn, @"^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$");
        }

        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;
        }
    }

Try this: 尝试这个:

If you want to force prefixing the protocol http://, https:// etc. 如果要强制给协议加上前缀http://,https://等。

^(http://|https://|ftp://)\w+\.\w+.*$

If you don't want to force prefixing the protocol http://, https:// etc. 如果您不想强加协议http://,https://等的前缀。

^(http://|https://|ftp://)?\w+\.\w+.*$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM