Skip to content

Commit

Permalink
fix(keyboard): suppress invalid input on <input type="number"> (#628)
Browse files Browse the repository at this point in the history
  • Loading branch information
ph-fritsche committed Mar 25, 2021
1 parent 51bffe9 commit f633a52
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/__tests__/keyboard/plugin/character.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,23 @@ test('type [Enter] in contenteditable', () => {
expect(getEvents('input')[2]).toHaveProperty('inputType', 'insertParagraph')
expect(getEvents('input')[6]).toHaveProperty('inputType', 'insertLineBreak')
})

test.each([
['1e--5', 1e-5, undefined, 4],
['1--e--5', null, '1--e5', 5],
['.-1.-e--5', null, '.-1-e5', 6],
['1.5e--5', 1.5e-5, undefined, 6],
['1e5-', 1e5, undefined, 3],
])(
'type invalid values into <input type="number"/>',
(text, expectedValue, expectedCarryValue, expectedInputEvents) => {
const {element, getEvents} = setup(`<input type="number"/>`)
;(element as HTMLInputElement).focus()

const state = userEvent.keyboard(text)

expect(element).toHaveValue(expectedValue)
expect(state).toHaveProperty('carryValue', expectedCarryValue)
expect(getEvents('input')).toHaveLength(expectedInputEvents)
},
)
12 changes: 12 additions & 0 deletions src/keyboard/plugins/character.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,18 @@ export const keypressBehavior: behaviorPlugin[] = [
oldValue,
)

// the browser allows some invalid input but not others
// it allows up to two '-' at any place before any 'e' or one directly following 'e'
// it allows one '.' at any place before e
const valueParts = newValue.split('e', 2)
if (
Number(newValue.match(/-/g)?.length) > 2 ||
Number(newValue.match(/\./g)?.length) > 1 ||
(valueParts[1] && !/^-?\d*$/.test(valueParts[1]))
) {
return
}

fireInputEvent(element as HTMLInputElement, {
newValue,
newSelectionStart,
Expand Down

0 comments on commit f633a52

Please sign in to comment.