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

Adds event passing to the format function. #803

Closed 17b0080 closed 8 months ago

17b0080 commented 1 year ago

Describe the issue/change

If you set a pattern for a phone number and try autofill, we won't be able to handle the case correctly when the user pastes '10001112233.' Specifically, we would receive '11000111223' in the onChange function instead of '10001112233.' If we don't check the 'isTrusted' property of the event, we may incorrectly process user input when they type '10001112233,' resulting in '1000111223,' which would be correct behavior. However, if you add the removal of extra characters outside the condition, we might end up with '0001112233,' which is not the correct behavior for some countries. For example, consider Kazakhstan, where a phone number can have the format: '7 (7##) ### ##-##.' Removing a potentially extra character could inadvertently remove an essential character in this context. This is why I added the passing of the 'event' to the 'format' function, aiming to handle events with 'isTrusted' set to 'false,' as we cannot do this in 'onChange.' In 'onChange,' there is simply no value after autofill; it is already formatted.

Example usage (If applicable)

const pattern = '+1 (###) ###-####'

const format = (value, event) => {
  const isTrusted = event ? event.isTrusted : true
  const valueToFormat = value

  // If the event is not 'isTrusted,' we consider it as autofill, and if needed, remove unnecessary characters.
  if (!isTrusted && value.length >10) {
    valueToFormat = value.slice(1)
  }

  return _format(valueToFormat)
}

Please check which browsers were used for testing