0

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
martijn
  • 1,417
  • 1
  • 16
  • 26
  • 2
    Instead of `keydown` use the [input event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event), it only fires when the value changes – Reyno Feb 28 '23 at 10:51
  • I also tried that, but it still alows me to input a non number. – martijn Feb 28 '23 at 10:55
  • Actually, your pattern succeeds when you have at least one digit or a dot or a comma. But it doesn't describe the full string. Instead of testing the keys one by one, describe the full string and test it. (Note that testing the keys doesn't prevent to write something like `,,,,,.....,,,`) – Casimir et Hippolyte Feb 28 '23 at 11:15
  • did you check out [this](https://stackoverflow.com/questions/43687964/only-numbers-input-number-in-react) question? – Ali Hosseini Feb 28 '23 at 11:16
  • I'm trying to allow the tab key to also be a valid input besides the number values. The current input works, but does not allow me to tab to the next field. I'm testing the keydown value, not the current field value. – martijn Feb 28 '23 at 11:21
  • 1
    *"I'm testing the keydown value, not the current field value."*: yes, and what if someone *pastes* a value or *drags* a value? You'll miss it. You are listening to the wrong event. – trincot Feb 28 '23 at 14:19
  • (a) instead of `preventing` you can `cleanup` to a valid format on input event. (b) did you tried to filter `e.key.toString() === 'Tab'`? – ursa Mar 10 '23 at 22:45

0 Answers0