Is there a way to limit a form input field to be between certain number range, say (0,100)
I’m filtering the input in the onkeydown event, to accept only numbers, the problem is I want to reject a number if that number would make the input to go out of range
So I need a way to see if the current value of the input plus the key the user is pressing will sum up between the range.
I tried using:
if((parseFloat(this.value) + parseFloat(String.fromCharCode(e.keyCode)) > 100){ return false; }
the thing is e.keyCode can return different codes for the same number, right now is returning 57 for the number 9, but 105 if i press the number on the numpad.
Is there a way to accomplish this?
Trying to anticipate what the resulting value is going to be is harder than you think. Remember the user might be pressing backspace, or the cursor might not be at the end of the field, or the user might have part of the value selected, to be replaced on next keypress, and so on. It’s also possible to manipulate the text field through mouse operations you won’t get any say in.
The traditional approach is to put your validation on the ‘keyup’ event instead of ‘keypress’. Then you get the full, post-change value of the field. You don’t get the chance to deny the keypress, but you can reset the field to the last-known-good value instead.
But either way it’s best not to try to constrain input too tightly, because this can make it terribly difficult to type. For example, “12.” is an invalid number you might want to deny… but if you did, it would become very difficult to type “12.3”! Better to allow any input, but signal when the current input is out of bounds, by some mechanism (eg. turning the text red is common).