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]);