When to use it#
- Use a Fieldset when one question is answered in several boxes, such as a name in a first and a last name box. Set
group. - Use a plain Fieldset to put related questions under one name, such as an address.
- Write a legend that asks the question or names the group, and put it first. A screen reader (software that reads the screen aloud) uses it as the name of the group.
- Don’t wrap every Field in a Fieldset. A screen reader announces a fieldset when focus enters it, so nested ones get noisy.
- Not for one control: use a Field, whose label names it. Not for checkboxes, radio buttons or a date: a CheckboxGroup, a RadioGroup and a DateInput already include a fieldset.
Information: Did you know?
To show an answer that can’t be changed, show it as text, such as “Applicant: Anna Andersson”, not as a disabled group. A disabled control gets no keyboard focus, so people using a keyboard or a screen reader can’t reach it to read it (see the Keyboard table).
Example#
import { Field, Fieldset, TextInput } from '@kvirn-ui/react'
import { useFieldsetTexts } from './texts.ts'
export function DefaultFieldset() {
const { texts } = useFieldsetTexts()
return (
<Fieldset.Root>
<Fieldset.Legend>{texts.address}</Fieldset.Legend>
<Field.Root required>
<Field.Label>{texts.street}</Field.Label>
<TextInput name="street" autoComplete="street-address" />
</Field.Root>
<Field.Root required>
<Field.Label>{texts.postalCode}</Field.Label>
<TextInput
name="postalCode"
autoComplete="postal-code"
inputMode="numeric"
className="kv-input--width-6"
/>
</Field.Root>
<Field.Root required>
<Field.Label>{texts.city}</Field.Label>
<TextInput name="city" autoComplete="address-level2" />
</Field.Root>
</Fieldset.Root>
)
}Use cases#
One question, several boxes
When the boxes together make one answer, set group. The legend then ends with “(optional)” if the group isn’t required, and the Fields inside never say “(optional)” on their own: one box of a name is never optional by itself.
import { Field, Fieldset, TextInput } from '@kvirn-ui/react'
import { useFieldsetTexts } from './texts.ts'
export function OneQuestion() {
const { texts } = useFieldsetTexts()
return (
<Fieldset.Root group>
<Fieldset.Legend>{texts.contactPerson}</Fieldset.Legend>
<Field.Root>
<Field.Label>{texts.firstName}</Field.Label>
<TextInput name="contactFirstName" />
</Field.Root>
<Field.Root>
<Field.Label>{texts.lastName}</Field.Label>
<TextInput name="contactLastName" />
</Field.Root>
</Fieldset.Root>
)
}Props in this example:
groupon Fieldset.Root
Describe the group and report its error
The description is read before answering, so it goes above the controls. The help text goes under them, and the error last. All three belong to the group and are linked to it, so a screen reader can read them when focus enters the group. Support differs between screen readers (see Known issues). After a failed send, move focus to the first control that is wrong.
import { Button, Field, Fieldset, Stack, TextInput } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { useFieldsetTexts } from './texts.ts'
type NameField = 'firstName' | 'lastName'
export function GroupError() {
const { texts } = useFieldsetTexts()
const inputs = useRef<Record<NameField, HTMLInputElement | null>>({
firstName: null,
lastName: null,
})
const [invalid, setInvalid] = useState(false)
const [focusRequest, setFocusRequest] = useState<{ field: NameField } | undefined>(undefined)
// Focus moves after the error has rendered, so the group's description includes it.
useEffect(() => {
if (focusRequest !== undefined) {
inputs.current[focusRequest.field]?.focus()
}
}, [focusRequest])
return (
<Stack
className="kv-stack--gap-8"
as="form"
noValidate
onSubmit={(event) => {
event.preventDefault()
const data = new FormData(event.currentTarget)
const firstEmpty: NameField | undefined =
data.get('firstName') === ''
? 'firstName'
: data.get('lastName') === ''
? 'lastName'
: undefined
setInvalid(firstEmpty !== undefined)
if (firstEmpty !== undefined) {
setFocusRequest({ field: firstEmpty })
}
}}
>
<Fieldset.Root group required invalid={invalid}>
<Fieldset.Legend>{texts.nameQuestion}</Fieldset.Legend>
<Fieldset.Prose>
<p>{texts.nameDescription}</p>
</Fieldset.Prose>
<Field.Root required>
<Field.Label>{texts.firstName}</Field.Label>
<TextInput
ref={(element) => {
inputs.current.firstName = element
}}
name="firstName"
autoComplete="given-name"
/>
</Field.Root>
<Field.Root required>
<Field.Label>{texts.lastName}</Field.Label>
<TextInput
ref={(element) => {
inputs.current.lastName = element
}}
name="lastName"
autoComplete="family-name"
/>
</Field.Root>
<Fieldset.HelpText>{texts.nameHelpText}</Fieldset.HelpText>
<Fieldset.ErrorMessage>{texts.nameError}</Fieldset.ErrorMessage>
</Fieldset.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
</Stack>
)
}Props in this example:
Information: Did you know?
A Fieldset’s invalid marks only its own parts. Mark a Field inside with the Field’s own invalid, and give it its own error message.
The question is the page heading
When a page asks one thing, the legend can be the page’s heading. Put the heading inside the legend and add the class kv-fieldset-legend--heading. Use h1 if it is the page’s main heading: this example is in a page that already has one, so it uses h2.
import { Field, Fieldset, TextInput } from '@kvirn-ui/react'
import { useFieldsetTexts } from './texts.ts'
export function QuestionAsHeading() {
const { texts } = useFieldsetTexts()
return (
<Fieldset.Root>
<Fieldset.Legend className="kv-fieldset-legend--heading">
<h2>{texts.contactHeading}</h2>
</Fieldset.Legend>
<Field.Root required>
<Field.Label>{texts.email}</Field.Label>
<TextInput name="email" type="email" autoComplete="email" />
</Field.Root>
<Field.Root>
<Field.Label>{texts.phone}</Field.Label>
<TextInput name="phone" type="tel" autoComplete="tel" />
</Field.Root>
</Fieldset.Root>
)
}Wire your own fieldset
For markup of your own, useFieldset gives the id, aria-describedby and state attributes to spread on a native fieldset and its legend. Name the descriptions from the first render, so server-rendered markup is complete.
import { Field, TextInput, useFieldset } from '@kvirn-ui/react'
import { useFieldsetTexts } from './texts.ts'
export function OwnElements() {
const { texts } = useFieldsetTexts()
const fieldset = useFieldset({ descriptions: ['helpText'] })
return (
<fieldset {...fieldset.fieldsetProps}>
<legend {...fieldset.legendProps}>{texts.address}</legend>
<Field.Root required>
<Field.Label>{texts.street}</Field.Label>
<TextInput name="street" autoComplete="street-address" />
</Field.Root>
<p {...fieldset.getDescriptionProps('helpText')} className="kv-field-help-text">
{texts.addressHelpText}
</p>
</fieldset>
)
}Props in this example:
descriptionson useFieldset (options)
Warning: Don't forget
Every fieldset needs a legend as its first child, or the group has no name (1.3.1 Info and Relationships, 4.1.2 Name, Role, Value). See What you need to do.
Accessibility#
What it does for you#
- APG pattern: none. A fieldset is native HTML:
<fieldset>with a<legend>is the group's name, and the browser maps it to thegrouprole. - Deviations: none from APG. A Prose in a Fieldset is the group's description (there is no Fieldset.Description), and the group's help text is
Fieldset.HelpText. - Native elements used:
<fieldset>(Fieldset.Root),<legend>(Fieldset.Legend),<p>(Fieldset.ErrorMessage, which behaves like Field.ErrorMessage), a<div class="kv-prose">for the description (Fieldset.Prose), a<p class="kv-field-help-text">for the help text (Fieldset.HelpText), and a<span>for the optional marker.
A Fieldset groups related questions or the options of one question. Its legend is the group's name, and its description (Fieldset.Prose), help text (Fieldset.HelpText) and error are the group's. Checkbox groups, radio groups and the date input are built on it.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| Fieldset.Root | <fieldset> → group | aria-describedby = every description id in DOM order, then the error id, only for parts rendered. Native disabled. data-invalid, data-required, data-disabled | Class kv-fieldset. Props: invalid, required, disabled, group, messages. The root is always a <fieldset>. No aria-invalid: ARIA doesn't support it on group, so the error reaches users through the description. disabled disables every control inside (native) |
| Fieldset.Legend | <legend>, the group's name | data-invalid, data-required, data-disabled | Class kv-fieldset-legend. Takes marker: appends <span class="kv-field-optional">(optional)</span> (in en; each language has its own text) when optional. Default optional in a group fieldset that isn't required, and none in a plain Fieldset |
| Fieldset.Prose | <div class="kv-prose" id>, or the element as gives | In the fieldset's aria-describedby, in DOM order, before the error. data-invalid, data-disabled | A Fieldset.Prose inside a Fieldset, and not inside a Field in it, registers itself and describes the group. Several are allowed, each with its own id. There is no Fieldset.Description |
| Fieldset.HelpText | <p class="kv-field-help-text" id>, or the element as gives. No role | In the fieldset's aria-describedby, in DOM order (with the Proses), before the error. data-invalid, data-disabled | The Field.HelpText part under the group's name (see field.a11y.md): a short instruction or example under the controls, for example the format of a date. A Fieldset.HelpText inside a Fieldset, and not inside a Field in it, registers itself and describes the group. Outside a Fieldset or Field it warns (help-text-outside-field) and renders a plain paragraph with no id. Never focusable, never a live region |
| Fieldset.ErrorMessage | <p id>, only while the fieldset is invalid | In the fieldset's aria-describedby, after every description. data-invalid | Class kv-field-error-message. The same prefix and icon as Field's |
useFieldset | the same attributes, for your own elements | fieldsetProps, legendProps, descriptionProps, getDescriptionProps(name), errorMessageProps | Options: invalid, required, disabled, hasDescription, descriptions (names, in render order), hasErrorMessage (default: invalid), group, marker, messages. Also returns optionalMarker and errorPrefix |
Rules, tested in fieldset.test.tsx:
- The legend is the first child of the fieldset in the DOM (the browser needs this for the name).
- A Fieldset's
invalidmarks its own parts only. It doesn't pass down to the Fields inside, so a group error doesn't mark every control. - A Field inside a
groupfieldset defaults tomarker="none": an option or a date box is never "(optional)". The group's legend carries the marker instead, when the group isn'trequired. - A plain Fieldset only groups questions (for example an address), so its legend has no marker, and its Fields mark themselves.
- Nested fieldsets: the nearest Fieldset's text parts win, and a plain Fieldset inside a group fieldset stops the group defaults.
- A Prose, a HelpText and the Fieldset.ErrorMessage attach to the nearest Field or Fieldset, as in
field.a11y.md: a Prose or a HelpText in a Field in the Fieldset describes that Field's control, not the group. - A
Fieldset.Prosein a Fieldset is the group's description. It is the Prose's text content: a heading, list or link inside it is read as plain text, so keep a description short. A Prose that isn't a description goes outside the Fieldset. A help text is plain text only. - Several descriptions and help texts are listed in DOM order, then the error, each with its own id. With the default order that is the description, the help text, then the error. A second Fieldset.ErrorMessage gives a dev warning.
useFieldset({ descriptions })andgetDescriptionProps(name)give the same markup on the server.
It announces nothing.
What you need to do#
- Give every fieldset a Fieldset.Legend that asks the question or names the group. Put the Fieldset.Legend first inside the Fieldset.
- A legend that is the page's heading:
<Fieldset.Legend className="kv-fieldset-legend--heading"><h1>…</h1></Fieldset.Legend>. - Use a Fieldset for options and for one question asked in several controls. Don't wrap every Field in one: a fieldset announces itself, and nested ones get noisy.
- Set
invalidand render a Fieldset.ErrorMessage together, with plain text that says what's wrong and how to fix it (3.3.1 Error Identification, level A; 3.3.3 Error Suggestion, level AA). - Set
groupon a Fieldset that holds options or the parts of one answer, so its Fields drop the optional marker and its legend takes it. - Mark which individual Fields inside are wrong with the Fields' own
invalid: the Fieldset's doesn't cascade.
Warning: Don't forget
Set invalid and render a Fieldset.ErrorMessage together, with text that says what is wrong and how to fix it. A group has no invalid state of its own, so without the text a screen reader user isn’t told anything is wrong (3.3.1 Error Identification, 3.3.3 Error Suggestion).
Visual and modes#
- Focus indicator: on the controls inside. The fieldset has none.
- Target size: no interactive area of its own.
- Colour: the legend, description, help text and marker use the normal text colour, and a help text keeps it when the group is invalid or disabled. The error uses the danger colour with a prefix and an icon, so colour is never the only signal (1.4.1 Use of Color, level A).
- forced-colors behaviour: nothing depends on colour. The error uses the system's text colour.
- reduced-motion behaviour: none.
- RTL: logical properties only.
Focus management#
- Initial focus: not moved.
- Trap: no.
- Restore to: not applicable.
- On error: Fieldset never moves focus. After a failed submit, you move focus to the first invalid control, or to an
ErrorSummary(see its contract). - Never obscured by: Fieldset renders no overlay.
WCAG success criteria#
- 1.3.1 Info and Relationships (A): native
<fieldset>/<legend>, the group's description and error in its accessible description (fieldset.test.tsx › wiring: name and description per state). - 1.4.1 Use of Color (A): the error has a prefix and an icon.
- 2.5.3 Label in Name (A): the visible legend text, with the marker, is the group's name.
- 3.3.1 Error Identification (A), 3.3.2 Labels or Instructions (A), 3.3.3 Error Suggestion (AA): as for Field.
- 4.1.2 Name, Role, Value (A): native
group, with a name and a description.
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
Fieldset handles no keys and moves no focus. A group's keys come from its controls (see the TextInput, CheckboxGroup and RadioGroup pages). Enter, Space, Escape, the arrow keys, Home and End are not handled by Fieldset.
| Key | Where | What happens |
|---|---|---|
| Tab / Shift+Tab | Fieldset with controls | Moves through the controls in DOM order. The fieldset, legend, description, help text and error aren't Tab stops Test: fieldset.test.tsx › Tab moves through the controls in DOM order and never stops on the group, its legend, its help text or its error |
| No key | fieldset[disabled] | Disabled controls inside are skipped (native) Test: fieldset.test.tsx › disabled disables every control inside, natively, fieldset.test.tsx › Tab skips the controls of a disabled fieldset (native) |
API reference#
import { Fieldset, useFieldset } from '@kvirn-ui/react'Fieldset.Root
Renders <fieldset> with the role group. It takes every attribute of a <fieldset> and passes ref to it. Your own aria-describedby ids come after its. The default theme is described on Theming.
| Prop | Type | Default | Description |
|---|---|---|---|
invalid | boolean | false | Sets data-invalid on the fieldset’s own parts and shows its Fieldset.ErrorMessage. It does not pass down to the Fields inside. |
required | boolean | false | Sets data-required and removes the optional text from the legend. |
disabled | boolean | false | Native disabled on the <fieldset>, which disables every control inside it. |
group | boolean | false | One question answered with several controls. The legend takes the optional text and the Fields inside drop theirs. |
messages | Partial<KvirnMessages['field']> | – | Overrides field.optional and field.errorPrefix for this fieldset. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-fieldset | always | The part class. The default theme styles it. |
data-invalid | present or absent | The fieldset is invalid. |
data-required | present or absent | The fieldset is required. |
data-disabled | present or absent | The fieldset is disabled. |
aria-describedby | ids | Every description and help text in DOM order, then the error, then your own ids. Only rendered parts are listed. |
Fieldset.Legend
Renders <legend>, the group’s name. It takes every attribute of a <legend> and passes ref to it. Put it first in the fieldset.
| Prop | Type | Default | Description |
|---|---|---|---|
marker | 'optional' | 'none' | 'optional' in a group, 'none' otherwise | Whether the legend ends with the optional text. It shows only when the fieldset is not required. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-fieldset-legend | always | The part class. |
kv-fieldset-legend--heading | class you add | The legend is the page’s heading: put the heading inside it. Theme option. |
kv-field-optional | on the span inside the legend | The optional text. It is part of the group’s name. |
data-invalid, data-required, data-disabled | present or absent | The state of the fieldset. |
Fieldset.Prose
Renders <div class="kv-prose">, the group’s description. Directly in a Fieldset, and not inside a Field in it, it registers itself and is listed in the fieldset’s aria-describedby.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-prose | always | The class that styles the text for reading. |
data-invalid | present or absent | The fieldset is invalid. |
data-disabled | present or absent | The fieldset is disabled. |
Fieldset.HelpText
Renders <p>, the group’s help text. It is the same part as Field.HelpText under the group’s name, and goes under the controls.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-field-help-text | always | The part class. The default theme sets it in smaller text. |
data-invalid | present or absent | The fieldset is invalid. |
data-disabled | present or absent | The fieldset is disabled. |
Fieldset.ErrorMessage
Renders <p>, rendered only while the fieldset is invalid, with the same icon and prefix as the Field’s. It is not a live region.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-field-error-message | always | The part class. |
kv-field-error-prefix | on a span inside | The prefix text, for example “Error:”. The theme hides it visually, not from screen readers. |
data-invalid | always | The part only renders while invalid. |
data-disabled | present or absent | The fieldset is disabled. |
useFieldset
Options
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | generated | The fieldset’s id. The description and error ids are derived from it. |
invalid | boolean | false | Marks the fieldset as invalid. |
required | boolean | false | data-required, and no optional text in the legend. |
disabled | boolean | false | Native disabled on the <fieldset>. |
group | boolean | false | One question answered with several controls. |
hasDescription | boolean | false | You render one description with descriptionProps, so aria-describedby lists it. |
descriptions | readonly string[] | – | The names of the descriptions you render with getDescriptionProps(name), in render order. aria-describedby lists them in this order, then the error. If you also set hasDescription, that description comes first. |
hasErrorMessage | boolean | true | false when you render no error message for an invalid fieldset. |
marker | 'optional' | 'none' | 'optional' in a group, 'none' otherwise | Whether the legend’s optional text shows. |
messages | Partial<KvirnMessages['field']> | – | Per-instance message overrides. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
fieldsetProps | FieldsetRootPartProps | – | Spread on the <fieldset>: class, id, aria-describedby, disabled and state. |
legendProps | FieldsetLegendPartProps | – | Spread on the <legend>, the first child of the fieldset. |
descriptionProps | FieldDescriptionPartProps | – | For the one description (hasDescription). |
getDescriptionProps | (name: string) => FieldDescriptionPartProps | – | For the description with this name. Its id is listed in descriptions. |
errorMessageProps | FieldErrorMessagePartProps | – | Spread on the error message, which you render only while invalid. |
descriptionId | string | – | The base id the description ids are derived from. |
errorMessageId | string | – | The error message’s id. |
isInvalid | boolean | – | Whether the fieldset is invalid. |
isRequired | boolean | – | Whether the fieldset is required. |
isDisabled | boolean | – | Whether the fieldset is disabled. |
isGroup | boolean | – | Whether group is on. |
marker | 'optional' | 'none' | – | The resolved legend marker. |
optionalMarker | string | undefined | – | The legend’s optional text, or undefined when it shows none. |
errorPrefix | string | – | The resolved field.errorPrefix text. Start the error message with it. |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one Fieldset, pass its messages prop.
A Fieldset uses the same two texts as a Field.
field.optional
The text that ends the legend of a group that is not required.
| Language | Default text |
|---|---|
| Svenska | (valfritt) |
| Suomi | (vapaaehtoinen) |
| Norsk bokmål | (valgfritt) |
| Norsk nynorsk | (valfritt) |
| English | (optional) |
field.errorPrefix
The text that starts the Fieldset.ErrorMessage.
| Language | Default text |
|---|---|
| Svenska | Fel: |
| Suomi | Virhe: |
| Norsk bokmål | Feil: |
| Norsk nynorsk | Feil: |
| English | Error: |
Known issues#
aria-describedbyon a<fieldset>may not be announced consistently. GOV.UK reports that NVDA, JAWS and VoiceOver announce it when the user enters the group and that TalkBack does not do so consistently. That is a report from others, not a result here: test all four with your users.- WebKit is not automated. Keyboard rows run in Vitest browser mode on Chromium. WebKit is not covered by the automated tests, so check Safari with your own users and assistive technology.
Information: Did you know?
Test with the screen readers your users have (see Testing), and read these items as reports, not results. Add what applies to your service to your accessibility statement, with the workaround.
Testing#
The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.
| AT + browser + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | fieldset.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | fieldset.test.tsx (axe and role, name and state): the legend is the group’s name, and the description is its description, in en |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 2 rows, each names a test in fieldset.test.tsx |
| Focus order and management | pass | n/a | pass | fieldset.test.tsx: keyboard › Tab moves through the controls in DOM order and never stops on the group, its legend, its help text or its error |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending |
What to check#
With a screen reader and the keyboard, try:
- Tab in from outside: the legend and "group" are read, then the description or the error (support differs).
- A group that is not required reads "(optional)" at the end of its legend.
- There is no Tab stop on the legend, description, help text or error.
- Submit with a box empty: after focus lands on the first wrong box, the group's error can be heard.
- A disabled fieldset: Tab skips every control.