Field
View as MarkdownA form field wrapper that provides accessible labeling, helper and error text, validation state and indicators for form inputs.
Features
Permalink to heading "Features"- Label, helper text and error text linked to the control with the right ARIA attributes
- Validates with the browser's constraints (
required,pattern,type="email",min/max,minlength/maxlength), your ownvalidatefunction and the schema or callback of the Form - Validation modes decide when errors show
- State as data attributes on every part: touched, dirty, filled, focused, valid, invalid, disabled, required and read-only
- Indicators for the required, invalid, valid and validating state
- Disabled by a surrounding Fieldset or
<fieldset disabled> - Works with the form primitives (Checkbox, Select, RadioGroup, ...) and native inputs
<primitives:field.root>
<primitives:field.label />
<primitives:field.control asChild="{true}">
<!-- Your form input here -->
</primitives:field.control>
<primitives:field.indicator type="required" />
<primitives:field.helperText />
<primitives:field.errorText />
</primitives:field.root>
Installation
Permalink to heading "Installation"typo3 ui:add field
Please copy the files manually from GitHub into your project: Field
Read more about installing Components and Primitives.
Examples
Permalink to heading "Examples"Mark a field as required
Permalink to heading "Mark a field as required"An empty required field stays quiet until the user has edited it or submitted the form.
Add helper text
Permalink to heading "Add helper text"Helper text sits below the input and is linked to it with aria-describedby.
Show an error
Permalink to heading "Show an error"Set invalid to show the error text, for example for a rule your backend decides.
Disable a field
Permalink to heading "Disable a field"disabled on the field disables the control inside it.
Require a checkbox
Permalink to heading "Require a checkbox"A required checkbox counts as missing until it is checked, for example "I accept the terms and conditions". The same goes for a required Select, Combobox, RadioGroup or CheckboxGroup while nothing is chosen.
Validate with native constraints
Permalink to heading "Validate with native constraints"The field reads the ValidityState of its control, so the constraints you already know are the rules: required as a prop of the field, and type="email", pattern, min, max, step, minlength and maxlength as plain attributes on the input part. The constraints other than required come from a native input or textarea. An Input or Textarea with a maxLengthBehavior of Invalid reports tooLong as well.
The form renders novalidate, which hands the display of errors to your error texts. An error text without a match shows the browser's message for the failed constraint. Give it a match to show your own text for exactly that constraint: valueMissing, typeMismatch, patternMismatch, tooShort, tooLong, rangeUnderflow, rangeOverflow, stepMismatch, badInput or customError.
Validation mode
Permalink to heading "Validation mode"validationMode decides when a field validates and shows its errors. Set it on the form for all its fields, or on a single field:
auto(default) - validates when the user leaves a field they have edited, and on every change while an error shows, so the message goes away as soon as the value is fixed. Tabbing through untouched fields stays quiet.onBlur- validates when the user leaves a field they have edited, not while they type.onChange- validates on every change.onSubmit- validates on submit only.
A submit validates all fields in every mode, shows every error and moves the focus to the first invalid one. While a mouse button or finger is down, error texts and indicators wait for the release. Keyboard users get them right away.
Show state with indicators
Permalink to heading "Show state with indicators"An indicator shows its content while the field is in the state given by its type: required, invalid, valid or validating. valid appears once the field has been validated and passed.
Async validation
Permalink to heading "Async validation"Ask the server whether a username is still free: pass a validate function that returns a message (or a list of messages) to mark the field invalid, and null to accept the value. It can return a promise. While the request runs, the validating indicator shows and a submit waits for the result. A result for a value the user has changed meanwhile is dropped.
A function cannot be rendered into markup, so pass validate from TypeScript: render the field with autoMount="{false}" and mount it in your entry file. validate receives the value and a snapshot of the native validity. It runs where the validation mode lets errors show (on blur by default), which makes it a good place for a request.
Replace the function later with updateProps({ validate }). Errors from the Form schema or callback and from the server (a 422 or onSubmit) reach the field on their own and show in the same error text.
Confirm a password
Permalink to heading "Confirm a password"Add listenTo="{0: 'password'}" to the passwordConfirm field. It names the sibling fields to watch, so when password changes, passwordConfirm validates again and its result stays current.
Put both rules in a validation callback, see Manual Client-Side Validation. A Zod .refine() on the whole schema runs after every field passes its own rule, so the mismatch error would wait for the length rule.
Show a field depending on another field
Permalink to heading "Show a field depending on another field"Whenever a field named in listenTo changes, the root of the listening field dispatches fluid-primitives:field:dependencychange. addDependencyChangeListener() on the field handle subscribes to it and returns a function that removes the listener. listenTo takes several names, e.g. listenTo="{0: 'arrival', 1: 'departure'}".
This shows a studentId field with listenTo="{0: 'ticketType'}" when the ticket type is student:
const studentId = form.api.getField('studentId')!;
studentId.addDependencyChangeListener(({ values }) => {
const show = values.get('ticketType') === 'student';
studentId.getRootEl()!.hidden = !show;
studentId.setDisabled(!show); // a disabled field is neither validated nor submitted
});
The callback receives dependencies (the value of each listened field, keyed by name) and values, the FormValues of the whole form. The event registration example in the Forms guide shows it in a working form.
Style a field by its state
Permalink to heading "Style a field by its state"Every part renders the state of the field as data attributes, so a label, an indicator or an error text can be styled with CSS alone. The API reference lists them per part.
From TypeScript, field.api and the FieldHandle of form.api.getField(name) expose the same flags: touched, dirty, filled, focused, valid, invalid, validating, disabled, required, readOnly and errors, together with validate(), clearErrors() and reset(). The root dispatches fluid-primitives:field:valuechange once a value has settled, 100 ms after the last keystroke by default.
API Reference
Permalink to heading "API Reference"The following tables cover the available props of the Fluid Primitives.
field.root
Permalink to heading "field.root"Provides shared field state for labels, helper text, errors, indicators and controls. Renders a <div> element.
| Name | Description | Required | Default |
|---|---|---|---|
name | stringThe unique field name used to associate labels, helper text, errors, and form values. | Yes | - |
disabled | booleanWhether the field is disabled. A field inside a disabled `<fieldset>` is disabled as well. | No | - |
invalid | booleanWhether the field is invalid, regardless of validation. Use it for errors the browser's constraint validation and the form's validation cannot compute, e.g. a pre-populated server error. | No | - |
required | booleanWhether the field is required. An empty required field stays quiet until the user edits it or the form is submitted. | No | - |
readOnly | booleanWhether the field is read-only. | No | - |
defaultValue | mixedThe initial value that child controls can use when rendered inside the field. | No | - |
validationMode | Enum\ValidationModeWhen errors become visible. `auto` validates on blur once the value was edited and on every change while an error shows, `onBlur` only on blur, `onChange` on every change, `onSubmit` only on submit. A submit validates every field in every mode. Without one, the field follows the `validationMode` of its form, which defaults to `auto`. | No | - |
listenTo | string[]Names of sibling fields within the same form whose value changes this field should react to. Dispatches a `fluid-primitives:field:dependencychange` event on this field's root element (see `addDependencyChangeListener()`) on every value change of a listened-to field, and treats that like a change of this field itself, so it revalidates under the same rules as when its own value changes - e.g. a `passwordConfirm` field listening to `password`. | No | - |
attributes | arrayAdditional attributes that should be rendered on the component where ui:attributes is used. | No | [] |
asChild | booleanIf true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. | No | - |
rootId | stringThe root ID of the component, used for hydration and identification. | No | - |
ids | arrayThe IDs of of the component parts for composition. | No | [] |
autoMount | booleanWhether the client initializes the component on its own. Set it to false to mount it yourself with `mount()` | No | true |
provider | stringThe `id` of the `.provider` this root takes its `rootId` and props from. | No | - |
class | stringThe CSS class(es) to be applied to the component. | No | - |
Rendered data attributes
| Attribute | Description |
|---|---|
data-disabled | Present when the field is disabled, or it is inside a disabled fieldset. |
data-invalid | Present when the field is invalid: a native constraint failed, or `validate`, the form or the server reported an error. |
data-valid | Present when the field has been validated and passed. |
data-required | Present when the field is required. |
data-readonly | Present when the field is read-only. |
data-touched | Present once the user has left the field at least once. |
data-dirty | Present when the value differs from the one the field started with. It goes away again when the user reverts the edit. |
data-filled | Present when the field has a value. |
data-focus | Present when focus is inside the field. |
data-name | The name of the field. |
field.label
Permalink to heading "field.label"Labels the associated form control. Renders a <label> element.
| Name | Description | Required | Default |
|---|---|---|---|
attributes | arrayAdditional attributes that should be rendered on the component where ui:attributes is used. | No | [] |
asChild | booleanIf true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. | No | - |
class | stringThe CSS class(es) to be applied to the component. | No | - |
Rendered data attributes
| Attribute | Description |
|---|---|
data-disabled | Present when the field is disabled, or it is inside a disabled fieldset. |
data-invalid | Present when the field is invalid: a native constraint failed, or `validate`, the form or the server reported an error. |
data-valid | Present when the field has been validated and passed. |
data-required | Present when the field is required. |
data-readonly | Present when the field is read-only. |
data-touched | Present once the user has left the field at least once. |
data-dirty | Present when the value differs from the one the field started with. It goes away again when the user reverts the edit. |
data-filled | Present when the field has a value. |
data-focus | Present when focus is inside the field. |
field.control
Permalink to heading "field.control"Wraps the slotted form control and wires up shared field attributes. Renders the element defined by the asChild prop.
| Name | Description | Required | Default |
|---|---|---|---|
attributes | arrayAdditional attributes that should be rendered on the component where ui:attributes is used. | No | [] |
asChild | booleanIf true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. | No | - |
class | stringThe CSS class(es) to be applied to the component. | No | - |
Rendered data attributes
| Attribute | Description |
|---|---|
data-disabled | Present when the field is disabled, or it is inside a disabled fieldset. |
data-invalid | Present when the field is invalid: a native constraint failed, or `validate`, the form or the server reported an error. |
data-valid | Present when the field has been validated and passed. |
data-required | Present when the field is required. |
data-readonly | Present when the field is read-only. |
data-touched | Present once the user has left the field at least once. |
data-dirty | Present when the value differs from the one the field started with. It goes away again when the user reverts the edit. |
data-filled | Present when the field has a value. |
data-focus | Present when focus is inside the field. |
field.helperText
Permalink to heading "field.helperText"Displays help or supporting text for the field. Renders a <div> element.
| Name | Description | Required | Default |
|---|---|---|---|
attributes | arrayAdditional attributes that should be rendered on the component where ui:attributes is used. | No | [] |
asChild | booleanIf true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. | No | - |
class | stringThe CSS class(es) to be applied to the component. | No | - |
Rendered data attributes
| Attribute | Description |
|---|---|
data-disabled | Present when the field is disabled, or it is inside a disabled fieldset. |
data-invalid | Present when the field is invalid: a native constraint failed, or `validate`, the form or the server reported an error. |
data-valid | Present when the field has been validated and passed. |
data-required | Present when the field is required. |
data-readonly | Present when the field is read-only. |
data-touched | Present once the user has left the field at least once. |
data-dirty | Present when the value differs from the one the field started with. It goes away again when the user reverts the edit. |
data-filled | Present when the field has a value. |
data-focus | Present when focus is inside the field. |
field.errorText
Permalink to heading "field.errorText"Displays the validation message of the field, or the text of its match when one constraint failed. Renders a <div> element.
| Name | Description | Required | Default |
|---|---|---|---|
match | Enum\ValidityMatchNarrows the error text to one failed native constraint, e.g. `valueMissing` or `typeMismatch`. Without it the text shows whenever the field is invalid and displays the error messages; with it the slotted text is shown as is. | No | - |
attributes | arrayAdditional attributes that should be rendered on the component where ui:attributes is used. | No | [] |
asChild | booleanIf true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. | No | - |
class | stringThe CSS class(es) to be applied to the component. | No | - |
Rendered data attributes
| Attribute | Description |
|---|---|
data-disabled | Present when the field is disabled, or it is inside a disabled fieldset. |
data-invalid | Present when the field is invalid: a native constraint failed, or `validate`, the form or the server reported an error. |
data-valid | Present when the field has been validated and passed. |
data-required | Present when the field is required. |
data-readonly | Present when the field is read-only. |
data-touched | Present once the user has left the field at least once. |
data-dirty | Present when the value differs from the one the field started with. It goes away again when the user reverts the edit. |
data-filled | Present when the field has a value. |
data-focus | Present when focus is inside the field. |
field.indicator
Permalink to heading "field.indicator"Shows its content while the field is in the state given by type: required, invalid, valid or validating. Renders a <span> element.
| Name | Description | Required | Default |
|---|---|---|---|
type | Enum\FieldIndicatorTypeThe state the indicator reflects: `required`, `invalid`, `valid` or `validating`. It stays in the DOM and is hidden unless the state matches, so CSS transitions survive. | Yes | - |
attributes | arrayAdditional attributes that should be rendered on the component where ui:attributes is used. | No | [] |
asChild | booleanIf true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. | No | - |
class | stringThe CSS class(es) to be applied to the component. | No | - |
Rendered data attributes
| Attribute | Description |
|---|---|
data-disabled | Present when the field is disabled, or it is inside a disabled fieldset. |
data-invalid | Present when the field is invalid: a native constraint failed, or `validate`, the form or the server reported an error. |
data-valid | Present when the field has been validated and passed. |
data-required | Present when the field is required. |
data-readonly | Present when the field is read-only. |
data-touched | Present once the user has left the field at least once. |
data-dirty | Present when the value differs from the one the field started with. It goes away again when the user reverts the edit. |
data-filled | Present when the field has a value. |
data-focus | Present when focus is inside the field. |
data-type | The state the indicator reflects. One of: "required", "invalid", "valid", "validating". |
Machine options
Permalink to heading "Machine options"| Name | Description | Default |
|---|---|---|
name | stringThe name of the field. It keys the field in its form and is what the field's value is read by. | - |
defaultValue | unknown | undefinedThe initial value, used while the DOM holds no control for this name yet. | - |
listenTo | string[] | undefinedNames of sibling fields in the same form whose value changes this field reacts to. | - |
ids | ElementIds | undefinedThe ids of the elements. Useful for composition. | - |
disabled | boolean | undefinedWhether the field is disabled. Also inherited from a surrounding native <fieldset disabled>. | |
invalid | boolean | undefinedWhether the field is invalid, regardless of computed validity. Use for app-level errors (e.g. server errors) the machine cannot compute itself. | - |
dirty | boolean | undefinedWhether the field's value has been changed from its initial value. Useful when the field state is controlled by an external library. | - |
touched | boolean | undefinedWhether the field has been touched. Useful when the field state is controlled by an external library. | - |
readOnly | boolean | undefinedWhether the field is read-only. | |
required | boolean | undefinedWhether the field is required. | |
validate | ((details: ValidateDetails) => ValidateResult | Promise<ValidateResult>) | undefinedCustom validation, run against the value and the native validity snapshot. May return a promise; a newer validation run supersedes an in-flight one. | - |
validationMode | ValidationMode | undefinedWhen validation results become visible. Without one, the field follows the validationMode of its form, and validates as auto outside a form. | "auto" |
onValidityChange | ((details: ValidityChangeDetails) => void) | undefinedCalled when the committed validity changes. | - |
dir | "ltr" | "rtl" | undefinedThe document's text/writing direction. | "ltr" |
id | stringThe unique identifier of the machine. | - |
getRootNode | (() => ShadowRoot | Document | Node) | undefinedA root node to correctly resolve document in custom environments. E.x.: Iframes, Electron. | - |
Machine JavaScript API
Permalink to heading "Machine JavaScript API"| Name | Type | Description |
|---|---|---|
ids | ResolvedElementIds | The resolved element ids, for composition with other components. |
disabled | boolean | Whether the field is disabled (including inherited fieldset disabled state). |
invalid | boolean | Whether the field is invalid. |
valid | boolean | null | Committed validity: null until validation has run. |
required | boolean | Whether the field is required. |
readOnly | boolean | Whether the field is read-only. |
focused | boolean | Whether the control is focused. |
touched | boolean | Whether the control has been blurred at least once. |
dirty | boolean | Whether the value differs from the initial value. |
filled | boolean | Whether the control has a non-empty value. |
validating | boolean | Whether an async validation is in flight. |
errors | string[] | The committed error messages. |
validity | ValiditySnapshot | null | The committed validity snapshot, null until validation has run. |
ariaDescribedby | string | undefined | The composed aria-describedby, for wiring custom controls. |
validate | VoidFunction | Runs validation now, surfacing valueMissing even on a pristine field. |
clearErrors | VoidFunction | Clears committed errors and returns validity to the pristine (unvalidated) state. |
reset | VoidFunction | Resets interaction state and validity to pristine. |
getRootState | () => RootState | Returns the state of the root. |
getLabelState | () => LabelState | Returns the state of the label. |
getControlState | () => ControlState | Returns the state of the control (input, textarea, select, or a custom host). |
getHelperTextState | () => HelperTextState | Returns the state of the helper text. |
getErrorTextState | (props?: ErrorTextProps) => ErrorTextState | Returns the state of the error text. |
getIndicatorState | (props: IndicatorProps) => IndicatorState | Returns the state of the indicator. |
name | string | The name of the field. |
getValue | () => FieldValue | The current value of the field. |
getErrorText | () => string | null | The first error message of the field, null if there is none. |
getRootEl | () => HTMLElement | null | The root element of the field. |
getFormMachine | () => FormMachine | undefined | The machine of the form the field sits in, undefined outside of a form. |
setDisabled | (disabled: boolean) => void | Disables or enables the field. |
setRequired | (required: boolean) => void | Marks the field as required or optional. |
setReadOnly | (readOnly: boolean) => void | Makes the field read-only or editable. |
setConstraint | (constraint: FieldConstraint | null) => void | Registers a rule only the control inside the field knows, such as a soft maxLength. The field runs it with the value on every validation, and a violation makes the field invalid like a native constraint does. A field has one, a new one replaces the old, null takes it back. |
addDependencyChangeListener | (callback: (detail: FieldDependencyChangeDetail) => void) => () => void | Calls callback whenever the value of a field named in the listenTo prop of this field changes. Returns a function that removes the listener again. For a field without listenTo it never fires, but the returned function is still safe to call. |