Skip to content

fix: prevent form submission when required Select has more than 300 options and no selection #8280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions packages/@react-aria/select/src/HiddenSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,13 +141,19 @@ export function HiddenSelect<T>(props: HiddenSelectProps<T>): JSX.Element | null
</div>
);
} else if (name) {
let data = selectData.get(state) || {};
// Use a hidden <input type="text"> rather than <input type="hidden">
// so that an empty value blocks HTML form submission when the field is required.
return (
<input
type="hidden"
type="text"
autoComplete={selectProps.autoComplete}
name={name}
disabled={isDisabled}
value={state.selectedKey ?? ''} />
value={state.selectedKey ?? ''}
onChange={() => {/** Ignore react warning. */}}
required={data.isRequired}
hidden />
);
}

Expand Down
28 changes: 27 additions & 1 deletion packages/react-aria-components/stories/Select.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ export const SelectRenderProps = () => (
</Select>
);

let manyItems = [...Array(100)].map((_, i) => ({id: i, name: `Item ${i}`}));
let makeItems = (length: number) => Array.from({length}, (_, i) => ({
id: i,
name: `Item ${i}`
}));
let manyItems = makeItems(100);

export const SelectManyItems = () => (
<Select>
Expand Down Expand Up @@ -174,3 +178,25 @@ AsyncVirtualizedCollectionRenderSelect.story = {
delay: 50
}
};

// Test case for https://github.com/adobe/react-spectrum/issues/8034
// Required select validation cannot currently be tested in the jsdom environment.
// In jsdom, forms are submitted even when required fields are empty.
// See: https://github.com/jsdom/jsdom/issues/2898
export const RequiredSelectWithManyItems = () => (
<form>
<Select name="select" isRequired>
<Label style={{display: 'block'}}>Required Select with many items</Label>
<Button>
<SelectValue />
<span aria-hidden="true" style={{paddingLeft: 5}}>▼</span>
</Button>
<Popover>
<ListBox items={makeItems(301)} className={styles.menu}>
{item => <MyListBoxItem>{item.name}</MyListBoxItem>}
</ListBox>
</Popover>
</Select>
<Button type="submit">Submit</Button>
</form>
);