Say I pressed "." (keycode 46 on the keyboard) first press will show the char, second press shows nothing unless you press another char that is different then it shows again on the next press.
I'm not really familiar using keypress, keydown, keyup, keycode but whatever can make it happen in pure javascript. I need something that is backward compatible up to IE6 if possible if not IE8 would be fine.
Cut story short: I need to validate an ip address(ipv4) input, keypress will only work if char is valid for an ip address characteristic, I don't want to use pop-up message if possible.
I've read something about "pattern" and matching it to the input but aside from the fact that I am not familiar with it also I am not sure if it's backward compatible.
Here's what I've done so far:
- Trapped inputs, only numbers and dot allowed - OK
- Trapped first block of the ip if > 255 or empty dot when press won't work - OK
- Trapped only 3 dots allowed - OK
I'm stucked on the part that it should not allow 2 consecutive dots when press that's why I can't proceed trapping on the 2nd, 3rd and 4th block of the ip address.
MY CODE
Script:
<script type="text/javascript">
function allowNumbersAndDot(e){
var n;
var dot = '.';
var ip = document.getElementById('ipaddr').value;
if (parseInt(ip) < 256 && ip.split(".").length < 4) {
if (ip == dot) {
document.all ? n = e.keyCode : n = e.which;
return (n > 47 && n < 58);
}
else {
document.all ? n = e.keyCode : n = e.which;
return ((n > 47 && n < 58) || n == 46);
}
}
else {
document.all ? n = e.keyCode : n = e.which;
return (n > 47 && n < 58);
}
}
function handleKeyPress0(e) {
if (allowNumbersAndDot(e) ) {
return true;
} else {
return false;
}
}
</script>
Body:
<body>
<input id="ipaddr" type="text" title="enter ip address" name="ipaddr" onfocus="this.value=''" maxlength="15" onkeypress="return handleKeyPress0(event);" />
<input id="pingbtn" type="submit" value="PING"/>
</body>
keypressis deprecated. You might want to usekeydowninstead. Don't know about compatibility with IE, though.keypressfor some years from now, but there is no date for dropping support.