Skip to content Skip to sidebar Skip to footer

Javascript To Accept Only Numbers Between 0 To 255 Range

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 entered

Solution 1:

Currently you have the test

(a < 48) || (a > 57)

for invalid values. So I would change those:

(a < 0 ) || (a > 255)

You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.

At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).

I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.

To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:

if(!validnum(this.value)) 
    this.value="";

in the input tag, thus:

<inputtype='text'id='numonly' 
      onkeyup='if(!validnum(this.value)) this.value="";'>

with the function changed to:

functionvalidnum(a) { 
    if(a < 0 || a > 255) 
        returnfalse;
    elsereturntrue;
} 

or more succinctly:

function validnum(a) {
    return ((a >= 0) && (a <= 255));
}

Edit: To alert and clear the box, if you must:

functionvalidOrPunchTheUser(inputElement) {
    if(!validnum(inputElement.value)) {
        window.alert('badness'); // punch the user
        inputElement.value = ""; // take away their things
    }
}

<input type='text' id='numonly' 
      onkeyup='validOrPunchTheUser(this)'>

However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:

function validateIPKeyPress(event) {
    var key = event.keyCode;
    var currentvalue = event.target.value;
    if(key < 96 || key > 105)
    {
        event.preventDefault();
        window.alert('pain');
        returnfalse;
    }
    elseif(currentvalue.length > 2 ||
            (currentvalue.length == 2 &&
             key > 101)) {
        window.alert('of death');
        event.preventDefault();
        event.target.value = event.target.value.substring(0,2);
    }
    elsereturntrue;
}

With the input tag:

<inputtype='text'id='octet'
          onkeydown='validateIPKeyPress(event)'>

Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.

Solution 2:

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:

<inputtype='text'id='numonly'value=""onkeypress='allowIp(event)'onkeyup='javascript:checkIp()'>
functionallowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46)  // both nubmer range and period allowed, otherwise prevent.
  { 
      e.preventDefault();
  }
}

functioncheckIp() 
{ 
  var ip = $("#numonly").val();

    /* The regular expression pattern */var pattern = newRegExp("^(([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/

Solution 3:

Single Integer

You can use the following solution to check if the user input for a single integer is between 0 - 255:

document.getElementById('example').addEventListener('input', event => {
  const input = event.target.value;
  console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<inputid="example"type="text"placeholder="Enter single integer" />

IP Address

Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:

document.getElementById('example').addEventListener('input', event => {
  const input = event.target.value;
  console.log(input === newUint8ClampedArray(input.split('.')).join('.'));
});
<inputid="example"type="text"placeholder="Enter IP address" />

Solution 4:

You need to validate the current value of the input, rather than the last key that was pressed:

<inputtype='text'id='numonly' onkeypress='allownums(this.value)'> 

Your function then just needs to be modified to: if(a < 0 || a > 255)

Solution 5:

A function like this should do it:

functionallownums(value){
   var num = parseInt(value,10);
   if(num <0 || num>255)
      alert('invalid')      
}

Then have your html look like:

<inputtype='text'id='numonly' onblur='allownums(this.value)'> 

Live example: http://jsfiddle.net/USL3E/

Post a Comment for "Javascript To Accept Only Numbers Between 0 To 255 Range"