【发布时间】: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