I have an event bound to an input that should only allow numbers. Simplified:
function (e) {
if (-1 === [48,49,50,51,52,53,54,55,56,57].indexOf(e.keyCode)) {
e.preventDefault();
}
}
This works fine, but if someone types !, @, #, $, etc. the keyCode is still the same and the event default is not prevented.
On a physical keyboard, I can prevent this pretty simply by also checking e.shiftKey
. However, on an iOS virtual keyboard, some of those characters exist (such as $
) even for <input type=number>
and they can be typed directly. Their keyCode is the same, but it seems like e.shiftKey
is still falsey.
There are a variety of possible solutions that would be acceptable to me:
- Have the virtual keyboard itself not display these characters (i.e. only display numbers and a period/decimal)
- Detect that an invalid virtual key was pressed and suppress the event behavior
- Determine the an invalid character will be added to the input's value and suppress the event behavior in this case
- Others?