JavaScript to accept only numbers between 0 to 255 range

后端 未结 8 1572
野趣味
野趣味 2021-01-22 13:14

My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is ente

相关标签:
8条回答
  • 2021-01-22 13:43

    I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.

    Pattern usage example you could fetch here: http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/

    The code itself would look something like:

    <input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
    
    function allowIp(e){
    if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46)  // both nubmer range and period allowed, otherwise prevent.
      { 
          e.preventDefault();
      }
    }
    
    function checkIp() 
    { 
      var ip = $("#numonly").val();
    
        /* The regular expression pattern */
      var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
    
      /* use  javascript's test() function to execute the regular expression and then store the result - which is either true or false */
      var bValidIP = pattern.test(ip);
    
      if(bValidIP){
         // IP has ok pattern
         $("#numonly").css("background", "green");
      }
      else {
         $("#numonly").css("background", "red");
      }
    }
    

    You could check it here on fiddle http://jsfiddle.net/Indias/P3Uwg/

    0 讨论(0)
  • 2021-01-22 13:48
        function fun_key()
        {
        var key=event.keyCode;
        if(key>=48 && key<=57)
        {
        return true;
        }
        else
        {
        return false;
        alert("please enter only number");
        }
        }
    
        and you can call this function on keypress event like:
        <asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()">                </asp"textbox>
    
    0 讨论(0)
提交回复
热议问题