我需要一个只允许IP地址的文本框。我可以在Web应用程序中创建它,但我无法在Windows应用程序中执行此操作。请帮我这样做..
答案 0 :(得分:2)
使用此方法验证IP
public bool IsValidIP(string addr)
{
//create our match pattern
string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
//create our Regular Expression object
Regex check = new Regex(pattern);
//boolean variable to hold the status
bool valid = false;
//check to make sure an ip address was provided
if (addr == "")
{
//no address provided so return false
valid = false;
}
else
{
//address provided so use the IsMatch Method
//of the Regular Expression object
valid = check.IsMatch(addr, 0);
}
//return the results
return valid;
}
答案 1 :(得分:1)
您可以使用ASP.NET Regular Expression Validator
:
<asp:RegularExpressionValidator ID="regexpName" runat="server"
ErrorMessage="This expression does not validate."
ControlToValidate="yourTextBox"
ValidationExpression="RegEx here" />
然后将ValidationExpression
设置为:(仅允许IP地址)
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\
答案 2 :(得分:1)
下面。 如果您最终得到4个字节(如0-255范围内的数字),那么请按文字分割,这是一个有效的IP。
bool IsTextAValidIPAddress(string text)
{
bool result = true;
string[] values = text.Split(new[] { "." }, StringSplitOptions.None); //keep empty strings when splitting
result &= values.Length == 4; // aka string has to be like "xx.xx.xx.xx"
if(result)
for (int i = 0; i < 4; i++)
result &= byte.TryParse(values[i], out temp); //each "xx" must be a byte (0-255)
return result;
}
或者,如果您可以/想要利用System.Net
bool IsTextAValidIPAddress(string text)
{
System.Net.IPAddress test;
return System.Net.IPAddress.TryParse(text,out test);
}