Form
Forms coordinate validation, default values, and submission across RuiField children without external form
libraries.
Try it
Usage
Wrap fields in RuiForm and handle validated values with onSubmit. Choose mode to control when validation runs.
import { RuiForm } from '@ecopages/radiant-ui/form';
import { RuiField } from '@ecopages/radiant-ui/field';
import { RuiLabel } from '@ecopages/radiant-ui/label';
import { RuiInput } from '@ecopages/radiant-ui/input';
import { RuiButton } from '@ecopages/radiant-ui/button';
<RuiForm mode="onSubmit" onSubmit={handleSubmit}>
<RuiField rules={{ required: 'Name is required' }}>
<RuiLabel>Full name</RuiLabel>
<RuiInput name="name" />
</RuiField>
<RuiButton type="submit">Create account</RuiButton>
</RuiForm>;Custom markup
<rui-form> coordinates validation across rui-field connectors and a composed native form. The RuiForm helper stamps [data-ref="form"]; it is not required.
import '@ecopages/radiant-ui/form';
<rui-form mode="onSubmit">
<form class="rui-form" data-ref="form" noValidate>
<rui-field>
<div class="rui-field">
<label class="rui-label" data-rui-field-label>
Name
</label>
<input name="name" type="text" data-rui-control class="rui-input" />
</div>
</rui-field>
<button type="submit">Submit</button>
</form>
</rui-form>;Submit buttons outside the native <form> are associated via the form attribute. Fields register through context — the form does not query control targets directly.
Load @ecopages/radiant-ui/styles.css once in your app to style the form and every composed control. When bundling styles per component, import @ecopages/radiant-ui/form/styles.css plus the stylesheet for every component used inside the form, such as field/styles.css, textarea/styles.css, or number-field/styles.css.
Validation timing
onSubmit validates once on submit and is best for short forms. Use onBlur or onChange when immediate feedback
helps data entry.
Compose with Radiant controls
Every RuiField child should be a Radiant control (RuiInput, RuiSelect, RuiDateInput, …). The form store
discovers values through the Field control protocol; unmarked native inputs are not registered.
Native form submission
RuiForm always contains a native <form>. These are two channels:
- Store (
onSubmit/rui-submit): named field values from the active store. The built-in store omits disabled controls, and the disabled options of a checkbox group, asFormDatadoes. Disabled elements of an array leave holes, so the others keep their index, andJSON.stringifywrites a hole asnull. A submission reads which controls are disabled once, when it starts, and validates, native validity included, and submits exactly those; a control enabled or disabled while validation is pending counts from the next submission. - Listed controls (
new FormData(form)andaction/methodnavigation): only what the browser lists
onSubmit skips native navigation. action / method without onSubmit POSTs listed controls only.
Listed:
- Inner native controls:
RuiInput,RuiTextarea,RuiCheckbox,RuiSwitch,RuiRadioGroup,RuiNumberField(through its native number input), and the checkboxes of aRuiCheckboxGroup, which share the group'sname - Form-associated hosts (
nameon the host):rui-date-input,rui-slider,rui-knob. An empty named date submits''. A range slider also submits{name}-max - Form-associated selections (
nameon the host):RuiSelect,RuiCombobox, standaloneRuiListboxand standaloneRuiTagGroup. UseFormData.getAll(name)to read one entry per selected value. An empty selection contributes no entries. RuiDateFieldis not listed; it copiesnameonto the nestedrui-date-inputRuiDateRangePickeris not listed;start-name/end-nameland on the nestedrui-date-inputhostsRuiFieldwrites no name: the control carries its own, and the field registers the control under it. The field element itself is not listed
These four selection hosts follow disabled fieldsets, including the first legend exception. required checks for at least one selected value. Native reset restores the initial selection in a plain form and the current store defaults in RuiForm, which writes them into every control once the browser has reset the form's controls, so a control that is reset to its markup default ends on the store default too. Browser restoration recovers the saved selection. The listbox and the chips inside a select or combobox are plain markup, so they are never listed in the form and do not follow a fieldset on their own.
Custom form-associated hosts
RuiField connects a control to the RuiForm store. Native forms use a separate channel: the browser lists a control in FormData only when a native form control has a name or a form-associated custom element supplies a value through ElementInternals. Register a third-party host before its field connects. Registration supplies store value access. The built-in store reads disability through :disabled, the host's disabled property, or an optional disabled(host) adapter reader. A supplied store continues to receive values and native validity and decides how to handle disability. In either case, the host carries its own name, which the field registers it under. It does not make the host form-associated.
import { customElement, prop } from '@ecopages/radiant';
import { FormAssociatedElement, type FormValue } from '@ecopages/radiant/form-associated-element';
import { announceControlConnect, registerFieldControl } from '@ecopages/radiant-ui/form';
@customElement('x-tone')
class ToneControl extends FormAssociatedElement {
@prop({ type: String, reflect: true, defaultValue: '' }) value!: string;
protected override onConnected(): void {
announceControlConnect(this);
}
/** Commit a choice, then dispatch `input` and `change` on the host so the field writes the new value. */
choose(value: string): void {
this.value = value;
this.dispatchEvent(new InputEvent('input', { bubbles: true, composed: true }));
this.dispatchEvent(new Event('change', { bubbles: true }));
}
protected override formValue(): FormValue {
return this.value;
}
protected override restoreFormState(state: FormValue): void {
this.value = typeof state === 'string' ? state : '';
}
}
registerFieldControl('x-tone', {
read: (host) => (host as ToneControl).value,
write: (host, value) => {
(host as ToneControl).value = String(value ?? '');
},
});A field writes a native control (<input>, <textarea>, <select>) on its native input and change events. It writes any other control, including a host like this one, on the same two events, but only when the event target is the control host (or a member native input of a wrapper or group), because a nested part's events also reach the field. A wrapper or group whose own native inputs dispatch the events, as rui-checkbox does, registers with events: 'members' in the adapter (FieldControlAdapter.events: 'host' | 'members', 'host' by default). A custom host must therefore dispatch input (and change on commit) on itself after it updates value, with no detail, and announce itself with announceControlConnect(this) (a bubbling, composed rui-control-connect event) when it connects, so a field that registered before the control existed seeds it from the form's value and reads its validity. Every Radiant control host does. A native <input>, <select> or <textarea> marked data-rui-control announces nothing: it must already be inside its field when the field connects, and one inserted later is picked up on the field's next sync (a store notification or a re-render).
FormAssociatedElement extends RadiantElement. Each concrete subclass has its own constructor, so several controls can inherit the base and register under different tags. The base owns the single ElementInternals, name, disabled, effective fieldset disability, submission syncing, reset, and restore after back/forward or autofill (formStateRestoreCallback writes the saved state back with restoreFormState() and marks the host :state(restored) until its form resets it, in browsers that support :state()). Its inherited static formAssociated getter is read when the concrete class is registered. Keep super.updated(changed) if you override updated(); that call syncs the form value after reactive writes. Likewise, call super.formDisabledCallback(disabled), super.formResetCallback() or super.formStateRestoreCallback(state, mode) when overriding those browser callbacks. In autocomplete mode the browser passes the autofilled string, not a saved state; override the callback when your formState() is not parseable from the submission string, as RuiSlider does for a range.
The first form value sync records the reset state, normally during the first connect update cycle, or a browser restore that comes first records it after the host adopts its authored attributes. By default, that state comes from formValue(). Override formState() when formValue() can be null for an unnamed host or returns a multi-entry FormData; return a value that restoreFormState() can read even if the name changes later. For visual disability caused by a parent <fieldset disabled>, read effectiveDisabled and watch @onUpdated('effectiveDisabled'). The catalog hosts support native submission, fieldset disability, and reset. Implement browser state restoration through formStateRestoreCallback() when the control needs it.
The control's own validity is read as described in Native validity.
Set data-rui-aria-target on the host when a native input is inside it. A registered host with a declared target binds the field's ARIA state onto it from fieldContext (fieldAria or fieldAriaBindings); see Field, which also covers the data-rui-field-managed marker the helpers set.
Default values
Pass defaultValues to pre-populate edit forms. Fields read their initial state from the form store. Multi-value controls (RuiSelect, RuiCombobox, RuiListbox, RuiCheckboxGroup, RuiTagGroup) store string[] — seed them with an array ({ language: ['ts'] }). A CSV string still writes because the host parses it; after that the stored value is an array. RuiSlider stores number[].
A control the visitor already edited in server-rendered markup, before the scripts loaded, is not overwritten by a default or by the store: its value is published to the store as a user change, with the form's own store and an injected one alike. See Field for how the edit is detected.
Native validity
Native validity is evidence, not configuration. The browser computes element.validity from the element's attributes and its value, and rui-form reads it and forwards the result: the failing ValidityState flag as the error type, the constraint behind it as params, and the control's own validationMessage as a fallback message. Nobody edits a native verdict and there is no switch for it; a control with no constraint attributes contributes nothing.
Sources: native input, textarea and select controls (required, type="email", minlength, maxlength, min, max, step, pattern), and form-associated hosts. A form-associated host that calls this.internals?.setValidity(flags, message) reports the same way, and a host that does not extend FormAssociatedElement passes a validity: (host) => ({ valid, type?, params?, message? }) function to registerFieldControl. Call setValidity before dispatching input, so change-time validation sees the new state. Native controls barred from constraint validation and controls that expose no validity contribute no fact. The built-in store skips disabled registrations, including their rules and native validity. Only controls marked data-rui-control, and Radiant's own controls, are bridged; a bare <input> inside a RuiField is neither read nor written.
| Flag | params | Constraint attribute |
|---|---|---|
valueMissing | none | required |
typeMismatch | { inputType } | type="email", type="url" |
patternMismatch | { pattern } | pattern |
tooShort | { minLength } | minlength (only after the user edits the value) |
tooLong | { maxLength } | maxlength |
rangeUnderflow | { min } | min (a number for type="number" and "range") |
rangeOverflow | { max } | max (a number likewise) |
stepMismatch | { step } | step (a number likewise; the attribute text on other types) |
badInput, customError | none | the browser, or setValidity |
With the built-in store a native problem is an input to its validation, with the timing of its own rules: it blocks submit and shows with aria-invalid and rui-invalid like any other error, and a rule or resolver message replaces its text but still blocks. A resolver cannot disable it; remove the attribute instead. With an injected store, the store decides when it shows, with the same timing as its own rules; see Inject a form state store.
rui-form renders <form noValidate>, so the browser's own validation bubbles never appear, while :invalid CSS and native submission keep working.
Inject a form state store
A host that already owns form state, such as a schema-driven forms layer, hands it to the form with form.connect(store, handlers), the only way to inject a store. The form then becomes a control bridge, and the store owns validation timing, touched and dirty state, defaults and which errors and warnings show. Without connect the form creates its own FormStore. For a minimal store from scratch, see Write a form state store.
<RuiForm ref={(form) => (form ? form.connect(store, { formatError, submitHandler, resetHandler }) : undefined)}>
<RuiField>
<RuiInput name="profile.name" />
<RuiFieldError />
</RuiField>
</RuiForm>connect returns a disposer, and a ref callback may return it as its cleanup, or keep it: const disconnect = form.connect(store, { formatError, submitHandler, resetHandler }). Calling connect again with the same store replaces only the handlers; with another store it also re-registers every control and writes the new store's values into them, except into a control the visitor edited before the form ever wrote it, whose value goes to the new store instead. The disposer returns the form to its own store in the state it left: its earlier values, errors, touched fields and submitted flag, or a fresh store built from defaultValues if it never had one. It does nothing once another connect replaced its binding. The formatError property applies to the form's own store only, and a form that is disconnected from the document holds no subscription to the host store.
The store implements FormStateStore. Paths are the dotted name of each field's control, and the store reads and writes a nested tree by them: profile.name is values.profile.name, and rows.0.title is values.rows[0].title. The built-in FormStore does the same, so getValues(), getSnapshot().values, rui-submit values, defaultValues, rules and resolvers all see the nested tree, while the HTML name attributes and the keys of errors, touched and dirty stay dotted. An entry in an errors record marks its field invalid even when its message is missing or empty. How an injected store combines errors from different origins is its own decision; the built-in FormStore lets an error from setErrors(source, errors) replace its own at the same path, clears it when the user edits that field, and borrows no message between them. FormStore.errors is read-only and returns the merged errors: add a source's errors with setErrors, replace them by calling it again with the same source, and remove them with setErrors(source, {}) or clearErrors(path?).
| Control event | The form does |
|---|---|
| Value change | setValue(path, value), then reportNative({ [path]: fact }) straight away. |
| Focus | focus(path, { source }), once when focus comes into the field from outside it. Moving between the field's controls, or into and out of the portaled popup of a rui-select, rui-combobox or rui-date-range-picker it owns, is the same visit. source is 'program' for focus the form moves itself (focusField), 'user' otherwise, and a field that already holds focus when the form connects, such as a server-rendered autofocus, opens its visit then. A store that connect puts in place of another mid-visit hears the focus; the replaced store hears no blur. |
| Blur | When focus leaves the field, or the field leaves the document mid-visit, and getFocusedPath() still returns the key the form resolved for it (a store that follows a row's rename holds the visit under the new key): writes and reports the control first if the user changed it since the last synchronisation, then blur(path). The blur of the field focus left is reported before the focus of the next. A window or tab losing focus is not a leave: no blur is reported for it. |
| Submit | Calls sync(), then either calls submitHandler or awaits validate() and emits rui-submit with the snapshot values or rui-invalid with the snapshot errors. validate() resolves { outcome: 'passed' }, { outcome: 'invalid' } or { outcome: 'overtaken' }: the last, a check a newer write superseded, ends the submission with neither event. |
Native reset | Calls resetHandler when it is set, otherwise reset(), then rewrites every control from the store, again after the browser's own reset, and reports every control's fact again. |
| Store notification | Writes a path's value into its control when that value changed since the form last saw it, and reports the control's fact after the notification. |
| Seed, rename, connect | A control is seeded from the store when it registers or connects (rui-control-connect), unless the visitor edited it in server-rendered markup before the form wrote it: then the control's value is written to the store with setValue(path, value), as a change, and the store's value is not written into it. A rename (a row that moved) takes effect as soon as the control's name attribute changes, and rebinds the control to its new path and seeds it from the store there; it never writes a value. Each reports the control's fact after the change, and a rename withdraws the old path. |
| Disconnect | Reports null for the control's path, unless another live control is bound to that path when the report runs, as when rows move. |
Native validity is pushed, never pulled. A fact is { type, params?, message? }; see Native validity for what each flag carries. reportNative(facts) maps each path to its fact, or to null when the control reports valid or left the form. The form calls it whenever a control's value or presence changes, from either side and after the change settles: synchronously right after setValue for a user change, so a store holds the fact for a value before it handles blur, and through a microtask for everything else, with one call carrying every fact queued meanwhile. The store binds each fact to the value it holds, re-validates a path only if it was already validated, whether it passed or failed, or is in a failed scope (so a field that was checked and passed shows an error at once when its control turns invalid, a report never counts as a change, and a reset, which forgets what was validated, is not shown as an error), keeps the fact until the path is reported again, and ignores a non-null fact for a path it does not hold, such as a row that was removed. The form skips a control that was removed or renamed in the meantime, and a report the store rejects goes to reportError.
sync() writes every control the user changed into the store and reports every bridged control's fact. rui-form calls it before submitHandler and before its own validate, and a host that validates the store itself outside submit calls it first.
A fact is an input to the store's validation, not an error to show, so the store decides when it shows. The form presents getSnapshot().errors as the store gives them, tolerates extra fields on an entry (source, ruleId, params, all), and ignores keys with no registered control, such as a form-level __root__, which the host renders itself. validate() must resolve { outcome: 'invalid' } while the store holds any error at the validated paths, native ones included, and a warning never counts.
The snapshot also carries warnings, keyed like errors. A warning is advice: it never marks the field invalid, never reaches aria-invalid, and never blocks submit. RuiFieldWarning is the region that shows it, and rui-field fills and hides it the way it does RuiFieldError. It renders role="status", a polite live region, and is not part of aria-describedby. Pass formatError to connect to produce the text for errors and warnings, so an issue without a message never shows blank: it receives the store's whole entry, untouched, and { path }, and an empty result falls back to the issue's message. FormStateStore is generic over the store's own entry type, so connect infers issue and each handler's store from the store and nothing is cast, for example form.connect(store, { formatError: (issue, { path }) => t(issue.ruleId ?? issue.type, { ...issue.params, path }) }).
With an injected store the form ignores mode, revalidate-mode, field defaultValue, defaultValues, defaultValuesData, resolver and field rules, because the store owns each of them. A store therefore has no touched, dirty, checkValidity() or submission members to provide, and rui-field defaults are never written to it. The form compares a control with what the control read right after the form last synchronised it, not with the store, so a submit writes only what the user changed: an untouched empty text input reads '', and is not written over a store value of undefined.
Pass submitHandler to connect to take over submit. The form calls sync(), then calls it with a context:
| Member | What it does |
|---|---|
submitNatively() | Submits the native <form> to its action and method. |
The host holds its own store, so the context carries no store: validate it, count attempts and move focus with form.focusField(paths). The form then emits neither rui-submit nor rui-invalid, and a rejection is reported with reportError. The handler owns submission, so the form does not gate it: every submit calls the handler, even while an earlier call is pending, and the handler decides what a second submit means, such as ignoring it while busy. Without a handler the form validates and emits as above. Pass resetHandler to take over the native reset event the same way: it is called with no argument instead of reset(), may be async, and the form rewrites the controls from the store when it settles and again after the browser's own reset. Both handlers apply only with an injected store. The built-in store does not rewrite controls after a native reset; only the injected path does.
Theming
Form surfaces map to semantic surface roles, never Tailwind palette steps:
| Part | CSS roles |
|---|---|
Root (.rui-form) | space-stack gap |
The form itself carries no color roles; fields, labels, and controls inside keep their own surface / control tokens. Override at the theme layer, not in component CSS.
API
RuiForm renders a native <form> inside the coordinating <rui-form> custom element. The view maps defaultValues, resolver and formatError to prop: bindings and keeps authored children inside that native form.
Attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
mode | onSubmit · onBlur · onChange · onTouched · all | onSubmit | When validation runs. |
revalidate-mode | onSubmit · onBlur · onChange · onTouched · all | onChange | When fields re-validate after a failed submit. |
data-default-values | string | JSON-serialized default values for SSR / JSX attribute channel. | |
action | string | Native form destination when onSubmit is not provided. | |
method | string | Native form HTTP method when onSubmit is not provided. |
Props
| Prop | Type | Description |
|---|---|---|
defaultValues | Partial<FieldValues> | Initial values; fields read their state from the form store. |
resolver | Resolver<T> | Custom validation resolver (e.g. from createRulesResolver). |
formatError | (issue, { path }) => string | Text for the errors and warnings of the form's own store; an empty result falls back to message. A connected store takes its formatter from connect. |
onSubmit | (values: T) => void | Promise<void> | Receives the store. Skips native navigation. When omitted, action or method POSTs listed controls after validation passes. |
Light-DOM contract
| Target | Required | Host writes | Author owns |
|---|---|---|---|
[data-ref="form"] | yes | id when wiring orphan submits | native <form noValidate> and field children |
button[type="submit"] outside form | no | form attribute | submit buttons on the host |
rui-field descendants | yes (for registration) | — | each field's control tree |
Nested hosts: rui-field and each field's control host.
Context
formContext exposes ready, revision, fields, errors, actions, and the live store once the form is ready (the injected FormStateStore, or the form's own FormStore). Subscribe to presentation with @onContextUpdate({ context: formContext }) or a context subscription. actions contains only register. Direct registrations return NativeValidity | null from the optional getValidity reader. Scoped consumers resolve the nearest provider (@consumeContext / ContextSubscriptionRequestEvent) and use context.store for getValue / setValue, reset, subscribe, and validate; narrow with instanceof FormStore for the rest of FormStore. Nested forms still resolve the nearest provider. Without a submitHandler, a submission ends in rui-submit or rui-invalid unless it was abandoned: the store resolved overtaken, the store was replaced by connect or its disposer before validation settled, or the form is not connected when validation settles, as a native form that left the document does not submit. An abandoned submission emits nothing and does not call onSubmit, and a form removed and inserted again in the same task keeps its submission. The form runs one submission at a time per store: a submit while one is pending, through validation and an awaited onSubmit, is ignored, with no second validation and no event. A new submit is accepted once the pending one settles, even when it threw. With the built-in store, FormStore.isSubmitting stays true until the submission settles, including an awaited onSubmit, and is always cleared. A validator that throws ends the submission with rui-invalid and detail.error set. A rejection from onSubmit clears isSubmitting and is reported with reportError, so window sees an error event and there is no unhandled rejection. An injected store has no submission state of its own in the form; the driver applies the same outcomes. A RuiField registers once, with a getName that reads its control's name. actions.register returns a handle, { name, change(), blur(), updateOptions(options), refresh(), unregister() }, that identifies the registration rather than its name, and the form resolves the key from getName on change(), blur(), updateOptions() and refresh(), on every store change, at submission and in focusField. Registering a control that has no name yet returns a handle whose name is '' and whose calls do nothing; register again once the control has a name. A changed name moves the field's value, errors, touched and dirty state to the new name with one notification and no moment where the value is missing, two keyed rows can swap names without either registration being lost, and a control that lost its name is released. With an injected store a rename never writes a value: the control is rebound to the new path and seeded from the store there, even when the store holds nothing, and deleting the old path is the host's decision. Hydration payloads contain presentation only (ready, revision, fields, errors); they never include the store or its actions. RuiField reads the matching field state and applies it to its control as aria-invalid; use fieldContext for a control's local error and invalid values.
Methods
| Method | Description |
|---|---|
connect(store, handlers?) | Injects a FormStateStore with its formatError, submitHandler and resetHandler, typed by the store's own issue type. Returns a disposer. |
focusField(paths) | Focuses the first registered field among paths in document order, with the built-in or an injected store. Unknown paths are ignored, and nothing happens when none has a field. Use it to move focus outside a submit, such as after a failed step. |
sync() | Writes the controls the user changed into the injected store and reports every bridged control's fact. Submit calls it first. |
Events
| Event | Detail | Description |
|---|---|---|
rui-submit | { values: T } | Emitted when validation passes. |
rui-invalid | { errors: Partial<Record<string, FieldError>>; error?: unknown } | Emitted when validation fails on submit. error is set when a validator threw instead of reporting errors: the submission counts as invalid. |
These are the form's own events. The controls inside it dispatch the platform's input and change; rui-change remains only for non-form components (tabs, tree, menus, table, calendar, cycle-toggle).
View helpers
| Component | Target stamped | Notes |
|---|---|---|
RuiForm | [data-ref="form"] on the native form | Passes defaultValues, resolver, formatError, onSubmit via prop: bindings. |
CSS classes
Public BEM classes (documented via @cssclass):
| Class | Description |
|---|---|
.rui-form | Root form surface (<form noValidate>). |
Theme roles
| Part | CSS variables consumed |
|---|---|
| Root | --space-stack |
Accessibility
- Submit buttons should use
type="submit"inside the form for keyboard submission. - Announce form-level errors at the top when multiple fields fail validation.
- Focus the first invalid field after a failed submit attempt.