I'm creating an number input field for a form. I've discovered that number inputs are kind of wonky and allow me to input text values. This breaks some things in my form because I need to use the numbers in a calculation.
In order to prevent text input, I've added a onKeyDown event that prevents non numeric inputs:
const inputPattern = /[0-9]|[,.]/;
const onKeyDown = (e) => {
if (!inputPattern.test(e.key.toString())) {
e.preventDefault();
}
};
html (in a React function component):
<input type="number" name="derp" onKeyDown={onKeyDown} />
This works, except it creates a new problem. Now, when I press Tab to go to the next field, or Enter to submit, it also gets blocked.
Could I resolve this using a different regex? Or is there a different, better way to prevent text input in a number input field?
I've tried:
- using the input pattern field -> this still allows text input
- using a text input -> this requires casting the field to a number before calculations which causes me a lot of grief.
- using inputmode="decimal" -> this just modifies the mobile input keyboard