JavaScript to accept only numbers between 0 to 255 range

后端 未结 8 1580
野趣味
野趣味 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:

    
    
    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/

提交回复
热议问题