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
I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:
(input.value * 10) + parseInt(e.key)
and not simply input.value + parseInt(e.key)
. It should be * 10
because you add one more digit at the back during keypress, e.g. 10
becomes 109
.Number.isInteger(parseInt(e.key))
because when 255
is selected, pressing 9
will not turn into 2559
but 9
instead.So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0
condition, you don't even need it here because the negative sign (-)
will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29
and press 1
, which will become 129
. This is because 29 * 10 = 290
, which already exceed 255
, preventing user from entering 129
, which is valid. The start position is particularly hard to track when the input type="number"
. But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.