[英]Regular expression not validating domain name
我具有以下實用程序功能:
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;
}
}
嘗試這個:
如果要強制給協議加上前綴http://,https://等。
^(http://|https://|ftp://)\w+\.\w+.*$
如果您不想強加協議http://,https://等的前綴。
^(http://|https://|ftp://)?\w+\.\w+.*$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.