2014-01-09 40 views
2

如何解決它:處理自動IP輸入?

<input id="ip" onkeyup="IP();"> 

這是腳本:

function IP(){ 
       document.getElementById('IP').value = document.getElementById('IP').value.replace(/[^0-9 .]/g,""); 
       var ip = document.getElementById('IP').value; 
       ipparts= new Array(); 
       ipparts = ip.split('.'); 
       L=((ipparts.length)-1);      
       if(L<=2){ 
        if (ipparts[L]>=26 && ipparts[L]<=99 || ipparts[L]>=100 &&ipparts[L]<=255 && dot==0){ 
         document.getElementById('IP').value +='.'; 

        } 
       } 
      } 

我需要劇本時,如果用戶把點忽略它自動把圓點。

回答

0

你可以檢查被按下的鍵是不是一個點。另外,你應該使用keydown,而不是keyup,因爲當key被按下的時候keydown會被觸發,key被釋放的時候觸發。

<input name="ip" /> 

然後在你的Javascript

var ipElement = document.querySelector('input[name=ip]'); 
ipElement.addEventListener('keydown', function(evt) { 
    // . = 190 
    if(evt.keyCode == 190) { 
     // Validate the rest of the IP 
     return false; 
    } 
    else { 
     // Check if the user has entered 3 digits or pressed space or something 

    } 
}); 
+1

'。 = ASCII中的= 190 ---甚至不接近http://www.asciitable.com/。它是ASCII中的「dec 46」 – zerkms

+0

爲什麼我覺得它是190. – Achrome

+0

如何將關鍵代碼發送到腳本?哪個函數? – Maysam

0

參閱本文檔IP validation

在這裏他已經習慣了jqueryvalidator.js並用例子來解釋。

$.validator.addMethod('IP4Checker', function(value) { 
     var 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]?)$"; 
      return value.match(ip); 
     }, 'Invalid IP address'); 

     $('#form1').validate({ 
      rules: { 
       ip: { 
        required: true, 
        IP4Checker: true 
       } 
      } 
     }); 

    });