s-yadav / react-number-format

React component to format numbers in an input or as a text.
MIT License
3.9k stars 410 forks source link

Can't type / in expiry field with NumberFormatBase #856

Closed m-orsh closed 2 months ago

m-orsh commented 3 months ago

In earlier versions with NumberFormat, the example demo provided with credit card expiry would allow slash / to be input. However with NumberFormatBase, this input is ignored, preventing the user from typing /. So they can type the first two numerals of the expiry date, / automatically appears and the caret does not advance, additionally they cannot type / on their own to move the caret forward another position. They can just keep typing numerals, but they may not know that.

Example: https://codesandbox.io/p/sandbox/card-expiry-field-eovgoh?from-embed

Type first two digits...type slash...slash is not accepted.

m-orsh commented 3 months ago

Can fix it by doing this:

onKeyUp={onSlash((e)=>{
    if(e?.target?.selectionStart === 2) e.target.selectionStart++
})}

but it's not the best solution I feel...

m-orsh commented 3 months ago

Tried using isValidInputCharacter prop but seemed like it wasn't triggered with each key press

s-yadav commented 2 months ago

It will indeed require onKeyDown handling. Will update doc for the same.

  const onKeyDown = (e) => {
    const { target } = e;
    const { value, selectionStart } = target;
    console.log(value);
    if (e.key === "/" && value[selectionStart] === "/") {
      // if there is number before slash with just one character add 0 prefix
      if (value.split("/")[0].length === 1) {
        target.value = `0${value}`;
        target.selectionStart++;
      }

      target.selectionStart++;
      e.preventDefault();
    }
  };
s-yadav commented 2 months ago

Updated doc to reflect this.