sanniassin / react-input-mask

Input masking component for React. Made with attention to UX.
MIT License
2.22k stars 258 forks source link

Backspace skips over numbers #191

Open alexhisen opened 4 years ago

alexhisen commented 4 years ago

With a mask like (999) 999-9999, if you start Backspacing from the end with all numbers in place, once you remove the last 4 digits, the next Backspace jumps over the number in front of the dash and it remains. Same with the close paren.

This is with the current npm-published version 2.0.4

Solnur commented 4 years ago

I faced with same problem on third version

thanatusdev commented 1 year ago

Hello guys, I was able to make a workaround for this by using the beforeMaskedStateChange feature, here's the function that I used:

  function beforeMaskedStateChange({ nextState, userInput }) {
    let { value } = nextState
    let selection = nextState.selection
    let cursorPosition = selection ? selection.start : null

    value = value.replace(/_/g, "")

    // keep minus if entered by user
    if (value.endsWith("-") && userInput !== "-") {
      if (cursorPosition === value.length) {
        cursorPosition--
        selection = { start: cursorPosition, end: cursorPosition }
      }
    }

    value = value.replace(/-/g, "").replace(/ /, "").trim()

    if (value.endsWith(")") && userInput !== ")") {
      if (cursorPosition > value.length) {
        cursorPosition -= 2
        selection = { start: cursorPosition, end: cursorPosition }
      }
    }

    return {
      ...nextState,
      selection,
    }
  }