Skip to content

Commit

Permalink
Fix cursor position getting reset if isAllowed returns false. #699
Browse files Browse the repository at this point in the history
  • Loading branch information
s-yadav committed Oct 29, 2022
1 parent 436a5e6 commit 96085a2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/number_format_base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,12 @@ export default function NumberFormatBase<BaseType = InputAttributes>(
const _formattedValue = _format(_numAsString);

if (isAllowed && !isAllowed(getValueObject(_formattedValue, _numAsString))) {
//reset the caret position
const input = event.target as HTMLInputElement;
const currentCaretPosition = geInputCaretPosition(input);

const caretPos = getNewCaretPosition(inputValue, formattedValue, currentCaretPosition);
setPatchedCaretPosition(input, caretPos, formattedValue);
return false;
}

Expand Down
18 changes: 18 additions & 0 deletions test/library/keypress_and_caret.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ describe('Test keypress and caret position changes', () => {
expect(caretPos).toEqual(2);
});

fit('should maintain caret position when isAllowed returns false', async () => {
const { input } = await render(
<NumericFormat
isAllowed={({ floatValue }) => {
return floatValue < 100;
}}
value={100.222}
/>,
);

simulateNativeKeyInput(input, '1', 2, 2);

expect(input.value).toEqual('100.222');

await wait(100);
expect(input.selectionStart).toEqual(2);
});

describe('Test character insertion', () => {
it('should add any number properly when input is empty without format prop passed', () => {
const wrapper = mount(<NumericFormat thousandSeparator={true} prefix={'$'} />);
Expand Down

0 comments on commit 96085a2

Please sign in to comment.