Skip to content

Commit 29fb422

Browse files
committed
Fix #711
1 parent cf0b3ba commit 29fb422

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/numeric_format.tsx

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -330,17 +330,22 @@ export function useNumericFormat<BaseType = InputAttributes>(
330330
}
331331

332332
// don't allow user to delete decimal separator when decimalScale and fixedDecimalScale is set
333-
const { decimalSeparator } = getSeparators(props);
333+
const { decimalSeparator, allowedDecimalSeparators } = getSeparators(props);
334334
if (
335335
key === 'Backspace' &&
336-
value[(selectionStart as number) - 1] === decimalSeparator &&
336+
value[selectionStart - 1] === decimalSeparator &&
337337
decimalScale &&
338338
fixedDecimalScale
339339
) {
340-
setCaretPosition(el, (selectionStart as number) - 1);
340+
setCaretPosition(el, selectionStart - 1);
341341
e.preventDefault();
342342
}
343343

344+
// if user presses the allowed decimal separator before the separator, move the cursor after the separator
345+
if (allowedDecimalSeparators?.includes(key) && value[selectionStart] === decimalSeparator) {
346+
setCaretPosition(el, selectionStart + 1);
347+
}
348+
344349
const _thousandSeparator = thousandSeparator === true ? ',' : thousandSeparator;
345350

346351
// move cursor when delete or backspace is pressed before/after thousand separator

test/library/keypress_and_caret.spec.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,25 @@ describe('Test keypress and caret position changes', () => {
8787
expect(input.selectionStart).toEqual(2);
8888
});
8989

90+
it('should update caret position when any of the decimal separator is pressed just before the decimal separator #711', async () => {
91+
const { input } = await render(
92+
<NumericFormat
93+
value={12}
94+
allowedDecimalSeparators={[',', '.']}
95+
decimalSeparator=","
96+
thousandSeparator="."
97+
decimalScale={3}
98+
fixedDecimalScale
99+
/>,
100+
);
101+
102+
simulateNativeKeyInput(input, ',', 2, 2);
103+
expect(input.selectionStart).toEqual(3);
104+
105+
simulateNativeKeyInput(input, '.', 2, 2);
106+
expect(input.selectionStart).toEqual(3);
107+
});
108+
90109
describe('Test character insertion', () => {
91110
it('should add any number properly when input is empty without format prop passed', () => {
92111
const wrapper = mount(<NumericFormat thousandSeparator={true} prefix={'$'} />);

0 commit comments

Comments
 (0)