【问题标题】:Regular expression not validating domain name正则表达式不验证域名
【发布时间】:2012-03-14 10:27:36
【问题描述】:

我有这个实用功能如下:

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

此表达式使用 MVC 中的模型绑定验证工作:

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

所以我的问题是为什么我的效用函数失败了?

更新:

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

【问题讨论】:

  • 请解释失败的地方。 :)
  • 我在上面添加了实用程序类代码。输入字符串是“www.website.com”。我运行了一个 NUnit 测试,它首先使用实用程序类的相同实例测试电子邮件地址。
  • 该类中没有任何内容会导致您的 IsValidDomainName 函数失败。我什至在 www.website.com 上试了一下,效果很好。
  • 天哪,我刚刚意识到测试中有一个前面的空格。所有其他变量也有空格,所以当我使用编辑器内监视数组时它们被排成一行。啊,麻烦您了!
  • 其实我还有一个问题。如果您尝试“www.website.com 2”,它会成功。这肯定是无效的?

标签: c# regex asp.net-mvc


【解决方案1】:

试试这个:

如果要强制为协议添加前缀 http://、https:// 等

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

如果您不想强制为协议添加前缀 http://、https:// 等

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多