0

I'm using React with, Unform + React Input Mask and inside the beforeMaskedStateChange function of the React Input Mask library I have the following masking function:

Here I take the values ​​typed by the user and do the masking at the same time the user types.

However, now I need the numbers to also be "negative", in this case, it is necessary for the user to insert the character -, and this character will be after the first number on the ladder, for example:

"BRL -9.99"

How can I do this?

It's a mix of allowing character typing with Regex + React-Input-Mask logic.

/** @DESCRIPTION Retorna a máscara com casas decimais [Percentual, Monetário e Número] */
  const maskNumber = useCallback((currentState, nextState, maxNumber = 8) => {
    let { value } = currentState;
    const { selection } = nextState;
    const { isPercentage, isCurrency, isNumber } = maskType;

    value = value
      .toString()
      .replace(/\D/g, '')
      .replace(/^0+/, '')
      .substring(0, maxNumber);

    const DECIMAL = 2;
    while (value.length < DECIMAL + 1 && value.length > 0) {
      value = `0${value}`;
    }

    let nextStep = DECIMAL;
    let nextSeparator = ',';
    while (value.length > nextStep) {
      const SEPARATOR_POSITION = value.length - nextStep;
      value = value.slice(0, SEPARATOR_POSITION) + nextSeparator + value.slice(SEPARATOR_POSITION);
      nextStep += DECIMAL * 2;
      nextSeparator = '.';

      selection.start = isPercentage ? value.length : nextStep + 3;
      selection.end = isPercentage ? value.length : nextStep + 3;
    }

    if (value) {
      if (isCurrency) value = `R$ ${value}`;
      if (isPercentage) value = `${value}%`;
      if (isNumber) value = value?.replace('R$ ')?.replace('%');
    }

    return { ...nextState, value };
  }, [maskType]);
THIAGO DE BONIS
  • 760
  • 7
  • 22
  • how about `-value` ? I would also suggest not reusing the name `value` everywhere its confusing – azium Dec 14 '21 at 17:16
  • @azium I can't fix it the way I said. Because, the number can be integer, or negative, it will be negative when the user types the character "-" and it must always be to the left of the last number. I can't fix it the way I said. Because, the number can be integer, or negative, it will be negative when the user types the character "-" and it must always be to the left of the last number. About repeating the value, is it used to take the current value and assign the changes, as you suggest then? – THIAGO DE BONIS Dec 14 '21 at 22:21

0 Answers0