Skip to content

Commit

Permalink
Support empty string for maxlength
Browse files Browse the repository at this point in the history
An input's maxlength can be an empty string, which should NOT limit typing.
  • Loading branch information
Aprillion committed Mar 18, 2021
1 parent 0ffb5f3 commit 516498c
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
38 changes: 38 additions & 0 deletions src/__tests__/type.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,44 @@ test('honors maxlength', () => {
`)
})

test('honors maxlength="" as if there was no maxlength', () => {
const {element, getEventSnapshot} = setup('<input maxlength="" />')
userEvent.type(element, '123')

expect(getEventSnapshot()).toMatchInlineSnapshot(`
Events fired on: input[value="123"]
input[value=""] - pointerover
input[value=""] - pointerenter
input[value=""] - mouseover: Left (0)
input[value=""] - mouseenter: Left (0)
input[value=""] - pointermove
input[value=""] - mousemove: Left (0)
input[value=""] - pointerdown
input[value=""] - mousedown: Left (0)
input[value=""] - focus
input[value=""] - focusin
input[value=""] - pointerup
input[value=""] - mouseup: Left (0)
input[value=""] - click: Left (0)
input[value=""] - keydown: 1 (49)
input[value=""] - keypress: 1 (49)
input[value="1"] - input
"{CURSOR}" -> "1{CURSOR}"
input[value="1"] - keyup: 1 (49)
input[value="1"] - keydown: 2 (50)
input[value="1"] - keypress: 2 (50)
input[value="12"] - input
"1{CURSOR}" -> "12{CURSOR}"
input[value="12"] - keyup: 2 (50)
input[value="12"] - keydown: 3 (51)
input[value="12"] - keypress: 3 (51)
input[value="123"] - input
"12{CURSOR}" -> "123{CURSOR}"
input[value="123"] - keyup: 3 (51)
`)
})

test('honors maxlength with existing text', () => {
const {element, getEventSnapshot} = setup(
'<input value="12" maxlength="2" />',
Expand Down
5 changes: 4 additions & 1 deletion src/utils/edit/calculateNewValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ export function calculateNewValue(

// can't use .maxLength property because of a jsdom bug:
// https://github.com/jsdom/jsdom/issues/2927
const maxLength = Number(element.getAttribute('maxlength') ?? -1)
//
// '' is a valid value in DOM with the same meaning as -1, not 0 => use ||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const maxLength = Number(element.getAttribute('maxlength') || -1)

let newValue: string, newSelectionStart: number

Expand Down

0 comments on commit 516498c

Please sign in to comment.