2013-02-02 140 views
0

我想验证使用核心JavaScript的IP地址。我想确保每个IP地址部分的值必须大于100。但它不能正常工作。请查找以下代码以获取更多详细信息。IP地址验证不起作用

function testIP(){ 
      var ip=document.getElementById("ipaddress").value; 
      var first= ip.substring(0,3); 
      var second= ip.substring(4,7); 
      var third= ip.substring(8,11); 
      var fourth= ip.substring(12,15); 
      var error=false; 
      if(first){ 

       var ippart1 = 0+first; 

       if(first<100){ 

       } 
       else{ 
        alert("Please enter a valid ip address.First part of ip address is incorrect"); 
        error=true; 
       } 
      } 
      else  
       error=true; 
      if(second){ 

       var ippart2 = 0+second; 

       if(ippart2<100){ 

       } 
       else{ 
        alert("Please enter a valid ip address.Second part of ip address is incorrect"); 
        error=true; 
       } 
      } 
      else  
       error=true; 
      if(third){ 

       var ippart3 = 0+third; 

       if(ippart3<100){ 

       } 
       else{ 
        alert("Please enter a valid ip address.Third part of ip address is incorrect"); 
        error=true; 
       } 
      } 
      else  
       error=true; 
      if(fourth){ 

       var ippart4 = 0+fourth; 
       if(ippart4<100){ 

       } 
       else{ 
        alert("Please enter a valid ip address.Forth part of ip address is incorrect"); 
        error=true; 
       } 
      } 
      else  
       error=true; 
      if(error==true){ 

       return false; 
      } 
      else 
       return true; 

     } 

我觉得问题是在字符串到整数的转换。我也试过parseInt函数。它也没有工作。请看看它。

+0

也许你可以使用一些正则表达式? http://stackoverflow.com/a/5284410/1331430 –

+0

究竟是什么问题?在提问时,说出你期望发生的事情以及发生的事情非常重要。 – Pointy

+0

你遇到什么错误? –

回答

1

所有我会建议检查地址使用该功能有效的第一:

function validate(value) { 
     RegE = /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/ 
     if(value.match(RegE)) 
      alert('Valid IP'); 
     else 
      alert('Invalid IP'); 
     } 

然后使用解析INT,但凭借良好的条件(>不<):

if(parseInt(first)>100){ 

       } 

也考虑重构你的代码:)

+0

**这是错误的方式**,它会允许像'999.999.999.999'这是不是一个有效的IP地址的东西 '^(( 25 [0-5] | 2 [0-4] [0-9] | [01] [0-9] [0-9])\){3}(25 [0-5] |?2 [0-4] [0-9] | [01]?[0-9] [0-9]?)$'会为你带来更好的结果! –

3

您应该使用split()http://www.w3schools.com/jsref/jsref_split.asp)这个值。然后你可以检查值。

为什么你的方式错了;

考虑我进入85.15.13.25

变量值:

first: 85. 
second: 15. 
third: 13. 
fourth: 25 

所以第一,第二和第三变量是错的,它们包含一个点。

+1

[请注意w3schools的建议。](http://w3schools.com)但这不是一个坏主意:-) – Pointy

+0

感谢您的支持。我用警报测试了代码。第一,第二和第三个值。所有打印都完美的出点。 – Technosavia

+5

@Pointy您的意思是不是[w3fools.com](http://w3fools.com)? – Andreas