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 beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
for invalid values. So I would change those:
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:
in the input tag, thus:
with the function changed to:
or more succinctly:
Edit: To alert and clear the box, if you must:
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:
With the input tag:
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 = "";.