第一种:
验证ip地址用正则:
if (System.Text.Encoding.Default.GetByteCount(CheckIp) > 250)
{
sb.AppendLine("请输入250个字符(或125个汉字)以内的ip地址");
}
Regex reg = new Regex("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
string[] checkIp = CheckIp.Split('|'); //用|分割多个ip地址判断
for (int i = 0; i < checkIp.Count(); i++)
{
if (!reg.IsMatch(checkIp[i].Trim()))
{
sb.AppendLine("ip地址格式不正确");
break;
}
}
CheckIp = CheckIp.Replace(" ", "").Trim();
验证url地址正则
if (System.Text.Encoding.Default.GetByteCount(GatewayUrl) > 200)
{
sb.AppendLine("请输入200个字符(或100个汉字)以内的接口提交地址");
}
GatewayUrl = GatewayUrl.Replace(Environment.NewLine, "").ToLower();
if (!GatewayUrl.StartsWith("http://") && !GatewayUrl.StartsWith("https://"))
{
GatewayUrl = "http://" + GatewayUrl;//(默认输入www.baidu.com这样的网址会默认加上http://开头)
}
else
{
if (GatewayUrl.StartsWith("http://http://") || GatewayUrl.StartsWith("http://https://"))
{
GatewayUrl = "http://" + GatewayUrl.Replace("http://", "").Replace("https://", "");//(输入两个会替换一个为空)
}
else if (GatewayUrl.StartsWith("https://https://") || GatewayUrl.StartsWith("https://http://"))
{
GatewayUrl = "https://" + GatewayUrl.Replace("http://", "").Replace("https://", "");
}
}
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
if (!reg.IsMatch(GatewayUrl))
{
sb.AppendLine("地址格式不正确");
}
第二种:
加上using system.Net命名空间
if (string.isnullorEmpty(TextBox.Text))
{
Response.Write("请输入文本框内容!");
return;
}
else
{
IpAddress ip;
if (!IpAddress.TryPase(TextBox.Text,out ip))
{
Response.write("输入的ip地址无效");
return;
}
}
uri ul
if (!uri.TryPase(TextBox.Text,urikind.(绝对的 相对的 不确定的 )out ul))
{
respon.write("url地址不正确!");
}
第一种方法是验证比较通过的,各方面都考虑到 比如相对的地址 大小写转换 断行处理
第二种方法是狼子和我说的简单的验证但ip不行输入123456也是有效地ip地址了 所以这种方法不严谨