skip to Main Content

I have an input like this. I work with several browsers, but Mozilla Firefox is the one that allows me to enter dates using the keyboard. I tried to use the readonly attribute, but this disables the ability to select a date from the calendar; try using the onKeyDown method – but it doesn’t work in the Mozilla browser.

 <input
  className="date__input"
  type="date"
  key={t.id}
  value={t.factStart?.toLocaleDateString('en-CA')}
  onChange={(e) => handleChangeInput(e, index, 'factStart')}
/>

2

Answers


  1. To prevent keyboard input, you can use the onKeyPress event handler, which will prevent data input if the character code does not match the control key codes (for example, Tab, Backspace, Enter, etc.).

    <input
      className="date__input"
      type="date"
      key={t.id}
      value={t.factStart?.toLocaleDateString('en-CA')}
      onChange={(e) => handleChangeInput(e, index, 'factStart')}
      onKeyPress={(e) => {
        const controlKeys = [0, 8, 13]; // 0 = Tab, 8 = Backspace, 13 = Enter
        if (!controlKeys.includes(e.charCode)) {
          e.preventDefault();
        }
      }}
    />
    

    In this example, each time a key is pressed, the onKeyPress handler is called, which checks whether the character code is one of the allowed ones. If this is not the case, then e.preventDefault() is called, which stops the character input.

    However, there are some nuances related to the fact that Firefox allows you to enter dates using the keyboard in fields with the "date" type. This is due to the peculiarities of the implementation of this element water in different browsers developer.mozilla.org . Therefore, if you want to completely deactivate keyboard input, you can try using a custom date input element or a third-party library.

    Login or Signup to reply.
  2. As this will break WCAG key board input spec, you shouldn’t do this.

    https://www.w3.org/WAI/WCAG21/Understanding/keyboard-accessible

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search