<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
//检查IP格式是否正确
function checkip(){
var ip=document.form1.text4.value;
var letters='1234567890.'; //定义数值的范围
var count=0;
for(var i=0;i<=ip.length;i++){
var ipletter=ip.charAt(i);
if(letters.indexOf(ipletter)==-1){
alert('请输入0-9之间的数字');
return false;
}
}//

for(var i=0;i<ip.length;i++){                    //注: 高手看 就是这个查找小数点的代码出问题了 
ip.substr(i,1)=='.'? count++:count;
if(count!=3){
alert('IP的地址必须为3个小数点');
return false;
}
}

first=ip.indexOf('.');                      //查找第一个小数点位置
last=ip.lastIndexOf('.'); //查找最后一个小数点位置
str=ip.substring(0,last);
second=str.lastIndexOf('.'); //查找第二个小数点位置
str1=ip.substring(0,first);
str2=ip.substring(first+1,second);
str3=ip.substring(second+1,last);
str4=ip.substring(last+1,ip.length);
if(str1<0||str1>255){
alert('IP地址的数值范围在0~255之内');
return false;
}
else if(str2<0||str2>255){
alert('IP地址的数值范围在0~255之内');
return false;
}
else if(str2<0||str2>255){
alert('IP地址的数值范围在0~255之内');
return false;
}
else if(str2<0||str2>255){
alert('IP地址的数值范围在0~255之内');
return false;
}
}function checktext4(){
document.form1.text4.value="";
}</script><style type="text/css"></style>
</head>
 
<body>
<form name="form1">
    <p>检查IP是否正确:
    <input type="text" name="text4" value="检查IP是否正确" onclick="checktext4()" />
    <input type="button" name="button3" value="检查IP是否正确" onclick="checkip()"/>
    </p>
 </form>
</body>
</html>

解决方案 »

  1.   


    for (var i = 0; i < ip.length; i++) { //注: 高手看 就是这个查找小数点的代码出问题了
                    ip.substr(i, 1) == '.' ? count++ : count;
                    if (i == (ip.length - 1)) {//循环完后再检查
                        if (count != 3) {
                            alert('IP的地址必须为3个小数点');
                            return false;
                        }
                    }
                }
      

  2.   

    用正则更简便http://blog.csdn.net/lauphai/archive/2009/06/09/4253925.aspx
    http://topic.csdn.net/t/20041005/21/3428299.html
    http://blog.csdn.net/soulspark/archive/2007/05/14/1608272.aspx