1

I'm trying to make a masked TextInput for BRL currency using regex, so every time the user types a number it is formated as follow:

Screen capture

First the number pressed appears inside the TextInput and then you can change the state to your desired value. Isn't there a way to change the text before it is displayed for the user?

Basically what I'm doing is:

const MoneyTextInput = ({onChangeText, ok}) => {
  let [text, setText] = useState('00,00');
  return (
    <TextInput
      value={text}
      keyboardType="number-pad"
      style={{
        width: '100%',
        height: '100%',
        fontSize: 22,
      }}
      onChange={({nativeEvent}) => {
        setText(prettifyCurrency(nativeEvent.text));
        onChangeText(prettifyCurrency(nativeEvent.text));
      }}
    />
  );
};

And the function with the regex is this:

function prettifyCurrency(value: String): String {
  if (!value) {
    return '00,00';
  }
  let newText = value.replace(/(\D)/g, '').replace(/^0+/, '');

  if (newText.length < 4) {
    for (let i = newText.length; i < 4; i++) {
      newText = '0' + newText;
    }
  }
  newText = newText
    .replace(/(\d{2}$)/g, ',$&')
    .replace(/(\d{1})(\d{3})([,])/, '$1.$2$3')
    .replace(/(\d{1})(\d{3})([.])/, '$1.$2$3')
    .replace(/(\d{1})(\d{3})([.])/, '$1.$2$3');
  return newText;
}

Shouldn't it wait for the value prop to be updated? Is there anyway I achieve what I want? Because I know in Android (Java) I had a function to change the text before it was displayed.

PS.: I'm using OnChange function because I found it was a little bit faster than onChangeText

Gabriel Amorim
  • 370
  • 2
  • 13
  • Maybe check this https://stackoverflow.com/questions/52533573/textinput-with-typing-digits-from-right-to-left-and-adding-zeroes-automatically and this https://medium.com/@maulikdhameliya/how-to-format-number-input-to-usa-phone-number-format-in-react-native-e68363b0c6e4 – Alexy May 29 '20 at 11:11
  • 1
    Yeah, I didn't want to use a library for that, but I think I will have to – Gabriel Amorim May 30 '20 at 12:00

0 Answers0