Form
A form container with layouts, validation and submit state.
Usage
Validation
A field shows its message once the user changes it and leaves; submit shows every message and focuses the first field in error.
Layout
auto puts labels beside the fields once the form is 520px wide, and above them when it is narrower.
Field Hints
The ? beside a label shows the full explanation on hover or focus; help stays under the control as one short constraint.
Read-Only
readonly shows the form as a record: controls take focus and copy but cannot change, no field is marked required, and submitting still works.
Async Validation
An async validator runs after the synchronous rules pass, debounces while the user types, and aborts when the value moves on.
Submit and Server Errors
@submit runs once every check passes; setErrors() inside the handler hands server errors back to their fields.
Autosave
autosave saves through @submit a second after editing pauses, checking only the changed fields; one with an error saves once it is fixed.
Loading and Merging Data
setBaseline() loads fetched data; fields the user changed are kept unless reconcile decides otherwise.
Drafts
persist keeps what the user typed under the form's id, so a reload or a closed tab brings it back.
Leave Confirmation
confirmLeave() resolves whether to go, and asks only about changes no draft holds.
onBeforeRouteLeave(() => formRef.value.confirmLeave())
<!-- Escape, the mask and the close button all ask first -->
<TxModal v-model="open" :before-close="() => formRef?.confirmLeave()">
<TxForm ref="formRef" :model="form">…</TxForm>
</TxModal>
Query Filters
A filter bar lines its fields up with inline, folds the rarely used ones behind More filters, and turns off the leave prompt with :leave-confirm="false".
Sign-In and Sign-Up
Mark every field with autocomplete, keep no draft, and never block paste: password managers and texted codes rely on autofill and paste.
Long Questionnaires
validate-on="submit" lets people answer uninterrupted, and on submit TxFormErrorSummary lists every problem, each linking to its field.
Schema Validation
schema takes any Standard Schema v1 validator and hands each issue to the field at its path.
<script setup lang="ts">
import { z } from 'zod'
const schema = z.object({
email: z.string().email('Enter a valid email address'),
age: z.number().int().min(18, 'You must be 18 or older'),
})
</script>
<template>
<TxForm :model="form" :schema="schema">
<TxFormItem label="Email" prop="email">
<TuffInput v-model="form.email" />
</TxFormItem>
<TxFormItem label="Age" prop="age">
<TxNumberInput v-model="form.age" />
</TxFormItem>
</TxForm>
</template>
Custom Controls
TuffEx controls join the item around them on their own; bind the default slot's props on a native element, or call useTxFormField() in a component.
<TxFormItem v-slot="{ id, ariaInvalid, ariaDescribedby, required }" label="Accent colour" prop="color">
<input :id="id" v-model="form.color" type="color" :aria-invalid="ariaInvalid" :aria-describedby="ariaDescribedby" :required="required">
</TxFormItem>
import { useTxFormField } from '@talex-touch/tuffex/form'
// In the custom control's setup
const field = useTxFormField('input')
const controlAttrs = computed(() => field?.attrs(attrs) ?? attrs)
const isDisabled = computed(() => props.disabled || !!field?.disabled)
In a Plugin
A plugin view's localStorage goes with the view, so keep the drafts in the plugin's storage and write them before the view closes.
import { flushTxForms, provideTxFormHost } from '@talex-touch/tuffex/form'
import { LifeCycle, usePluginDraftStorage } from '@talex-touch/utils/plugin/sdk'
const app = createApp(App)
provideTxFormHost({ storage: usePluginDraftStorage() }, app)
LifeCycle.onBeforeClose(flushTxForms)
app.mount('#app')
A plugin's drafts are its own, and the host does not clear them; when a draft holds an account's data:
- Use
user:<account id>as the namespace, andanonwhen signed out; givenullwhile the account is not known, and no draft is kept meanwhile. - When the account changes, remove every other account's drafts, then switch the namespace. Do it each time the plugin starts too: the account may have changed while it was not running.
- Where the current account cannot be read, leave
persistoff for these forms.
Replace the provideTxFormHost call above with:
import { clearTxFormDrafts, provideTxFormHost } from '@talex-touch/tuffex/form'
import { usePluginAccount, usePluginDraftStorage } from '@talex-touch/utils/plugin/sdk'
import { ref } from 'vue'
const storage = usePluginDraftStorage()
const account = ref<string | null>(null)
provideTxFormHost({ storage, namespace: account }, app)
// Called once with the current account, then after every change
usePluginAccount().onDidChange((session) => {
if (!session.isSettled)
return
const next = session.user ? `user:${session.user.id}` : 'anon'
void clearTxFormDrafts({ storage, namespace: ns => ns.startsWith('user:') && ns !== next })
account.value = next
})
Best Practices
- Keep
modelthe same reactive object; a new object is a new record, which resets the baseline and clears every message. - Pass fetched data to
setBaseline()instead of writing it intomodel, sodirtyandreset()measure against it. - Put shared rules in form-level
rules; an item'srulesreplace the form-level rules for the same path rather than adding to them. - Put an explanation longer than one sentence in
hint, beside the label;helptakes only a short constraint the user must see while typing. Errors and warnings stay under the control, and no explanatory paragraph goes under a control. - Declare a validator that returns a promise
async, and passsignalto its request. - Turn
persiston once the record has loaded, so the draft is laid over the saved values rather than empty ones.
API Reference
TxForm
Props
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | generated | The <form> element's id, and the prefix of every field id: <id>-<prop>. |
model | Record<string, any> | - | Reactive form data; items read their field by the prop path. |
rules | FormRules | - | Form-level rules keyed by field path. |
schema | FormStandardSchema | - | A Standard Schema v1 validator (Zod, Valibot, ArkType…) checked against the whole model. Issues with no matching field are listed in the error summary and block submit. |
layout | 'auto' | 'side' | 'stacked' | 'inline' | 'auto' | Field layout; auto is side once the form is 520px wide and stacked below that; inline suits filter bars. |
labelPosition | 'left' | 'right' | 'top' | - | Older spelling of layout: top is stacked; left and right are side with that alignment. |
labelAlign | 'start' | 'end' | 'end' | Label alignment in the side column; start by default with labelPosition="left". |
labelWidth | string | number | 16em | Widest the side label column may grow, numbers in pixels; it stays narrower when every label is, and never exceeds 40% of the form. |
requiredMark | 'asterisk' | 'optional' | 'none' | 'asterisk' | Marks required fields with an asterisk, optional fields with messages.optional, or neither. |
validateOn | 'blur' | 'submit' | 'blur' | When the first message appears: on leaving a changed field, or on the first submit. |
messages | Partial<FormMessages> | - | Overrides the built-in text. |
size | 'small' | 'medium' | 'large' | 'medium' | Passed to the controls inside that have sizes. |
disabled | boolean | false | Disables every control inside that reads the form, and blocks submit. |
readonly | boolean | false | Shows the values as a record to read: every control inside that reads the form can be focused and copied but not changed, and no field is marked required. Submitting still works. |
reconcile | FormReconcile | - | Decides what model holds when setBaseline() or a draft brings values for fields the user changed. |
persist | boolean | FormPersistOptions | false | Keeps what the user typed under id; true takes the defaults. |
leaveConfirm | FormLeaveConfirm | false | host's, then window.confirm | Asked before leaving with changes no draft holds; false never asks, as for a filter. |
autosave | boolean | FormAutosaveOptions | false | Saves through the submit handler once editing pauses, instead of on a submit button. Only the changed fields are checked; one with an error is saved once it is fixed. true waits a second. |
onSubmit | (values: FormValues, event?: Event) => unknown | - | Called once every check passes, with a copy of the values; a returned promise is awaited, and submitting is true meanwhile. @submit binds it. A successful submit makes the submitted values the baseline, unless the handler called setBaseline() itself. |
Events
| Event | Payload | Description |
|---|---|---|
submit-success | (values: FormValues) | A submit or an autosave went through: every check passed, and the submit handler, when given, succeeded. |
validate | (valid: boolean) | Fires after validate() has checked every field. |
persist-error | (error: unknown) | A draft could not be read or written; fires once per run of failures. |
Slots
| Slot | Props | Description |
|---|---|---|
default | { dirty, valid, submitting, submitted, errors, rootError } | Form items and actions. |
draft | { draft, notice, restore, discard } | Replaces the notice above the fields while a draft has filled them in or waits. |
Exposed Methods
| Name | Type | Description |
|---|---|---|
dirty | boolean | Read-only; model differs from the baseline. |
valid | boolean | Read-only; no error blocks submit, whether or not it shows yet. |
submitting | boolean | Read-only; the submit handler is running. |
submitted | boolean | Read-only; the form has been submitted at least once; reset() clears it. |
errors | Record<string, string> | Read-only; the errors showing, by field path. |
rootError | string | Read-only; the form-level error. |
validate | () => Promise<boolean> | Validates every field, shows the messages, and resolves to whether all passed. |
validateField | (path: string) => Promise<boolean> | Validates one field and shows its message. |
submit | () => Promise<boolean> | What a native submit does: validates, then calls the submit handler; resolves to whether it succeeded. With autosave, saves the changes now. |
reset | () => void | Restores model to the baseline and clears every message. |
resetFields | () => void | Older name of reset(). |
setBaseline | (values?: FormValues) => void | Makes fetched values the baseline; without them, the current model becomes the baseline. |
setErrors | (errors: Record<string, string | null | undefined>, options?: { source?: 'server' | 'client' }) => void | Shows outside errors until the user edits the field; a client error also blocks submit. Errors for fields that are not mounted are kept and shown when the field mounts. |
setRootError | (message?: string | null) => void | Sets or clears the form-level error. |
clearValidate | (paths?: string | string[]) => void | Hides messages without changing model. |
draft | FormDraftState | Read-only; what the draft filled in or still offers, when it was written, whether writing fails. |
flush | () => Promise<void> | Writes the draft now. |
confirmLeave | () => Promise<boolean> | Call before leaving inside the app; resolves true to go. With autosave, saves pending changes first. |
restoreDraft | () => Promise<boolean> | Fills in the fields the draft still offers; resolves whether any were. |
discardDraft | () => Promise<void> | Puts the saved values back where the draft filled them in, and deletes it. |
TxFormItem
Props
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | '' | Label text; no label renders without it. |
prop | string | - | The field's path in model: name, meta.homepage, links[0].url. |
rules | FormRule | FormRule[] | - | Rules for this field; they replace the form-level rules for the same path. |
required | boolean | false | Shows the required marker and adds a required rule. |
help | string | - | Helper text under the control; an error or warning takes its place while it shows. |
hint | string | - | A detailed explanation in a popover from a ? beside the label, shown on hover or focus. |
width | 'xs' | 'sm' | 'md' | 'lg' | 'full' | - | Control width: 80, 160, 240 or 360px, or the whole column. |
showMessage | boolean | true | Shows the message under the control; with it off, the control is still marked invalid. |
inline | boolean | false | Centres the label on the control; in a stacked layout, puts it beside the control. |
persist | boolean | true | false keeps the field out of the draft, as a secret is. |
Events
| Event | Payload | Description |
|---|---|---|
validate | (valid: boolean) | Fires after this field validates: on leaving it changed, or when the form validates. |
Slots
| Slot | Props | Description |
|---|---|---|
default | { id, labelId, ariaInvalid, ariaDescribedby, invalid, required } | The field control; bind the props on a native element to link it to the label and message. |
TxFormRow
Props
| Prop | Type | Default | Description |
|---|---|---|---|
label | string | '' | Names the row as a group; in side layout it sits in the label column. |
condensed | boolean | false | Lets each item shrink to 110px instead of 220px before the row wraps. |
Slots
| Slot | Props | Description |
|---|---|---|
default | - | The row's TxFormItems, with their labels above. |
TxFormErrorSummary
Props
| Prop | Type | Default | Description |
|---|---|---|---|
title | string | messages.summaryTitle | The summary's heading. |
Types
FormRule, one entry of rules:
| Field | Type | Description |
|---|---|---|
required | boolean | Rejects empty values. |
type | 'email' | 'url' | 'number' | 'integer' | The value's format. |
min / max | number | Numeric range. |
minLength / maxLength | number | Characters in a string, or items in an array. |
pattern | RegExp | A pattern the value must match. |
message | string | Message when this rule fails, replacing the built-in text. |
level | 'error' | 'warning' | warning shows its message but never blocks submit. |
deps | string[] | Fields whose edits re-check this one while it shows a message. |
validator | (value, rule, model, { signal, path }) => boolean | string | Promise<boolean | string> | Return false or a message to fail; declare it async when it awaits. |
FormReconcileContext, the argument of reconcile; every value is a copy, free to change:
| Field | Type | Description |
|---|---|---|
source | 'baseline' | 'draft' | baseline is setBaseline(); draft is a stored draft whose fields were saved again since. |
incoming | FormValues | The values arriving; they become the new baseline whatever model ends up holding. |
current | FormValues | model as the user left it. |
baseline | FormValues | The baseline the user's edits were made against. |
dirtyPaths | string[] | Paths the user changed that incoming also carries. |
merged | FormValues | The default, taken when nothing is returned: incoming with dirtyPaths kept, or for a draft, model as it is. |
origin | FormValues | For a draft: the saved values its edits were made against, for a three-way merge. |
FormPersistOptions, the object form of persist:
| Field | Type | Description |
|---|---|---|
recordId | string | number | Keeps each record's draft apart: 42 for /posts/42/edit. |
namespace | string | Whose drafts these are; defaults to the host's, then default. |
version | number | Bump it when the model's shape changes; a draft from another version is dropped. Default 1. |
ttl | number | '7d' | '12h' | '30m' | How long a draft lasts after its last write, in milliseconds or units. Default '7d'. |
storage | 'local' | 'session' | 'memory' | FormDraftAdapter | Defaults to the host's, then local; memory lasts until the page reloads. |
exclude | string[] | Paths never written, on top of the secret fields. |
restore | 'auto' | 'manual' | manual waits for the notice or restoreDraft(). Default auto. |
FormDraftAdapter, a store of your own; every method may return a promise:
| Field | Type | Description |
|---|---|---|
get / remove | (key: string) => string | null / (key: string) => void | Reads or deletes one draft. |
set | (key: string, value: string) => void | Throw when the value was not stored; the form keeps it in memory meanwhile. |
clear | (prefix: string) => void | Optional; removes the keys starting with prefix, for clearTxFormDrafts(). |
keys | (prefix: string) => string[] | Optional; lists the keys starting with prefix, for clearTxFormDrafts() to pick namespaces with a function. |
FormAutosaveOptions, the object form of autosave:
| Field | Type | Description |
|---|---|---|
delay | number | How long editing pauses before the changes are saved, in milliseconds. Default 1000. |
FormMessages, the built-in text; the English defaults are FORM_DEFAULT_MESSAGES:
| Field | Type | Description |
|---|---|---|
required / invalid / pattern | (label: string) => string | Missing value, failed validator, mismatched pattern. |
hint | (label: string) => string | The accessible name of the ? button beside a label. |
type | (label: string, type: FormRuleType) => string | Wrong type. |
min / max | (label: string, limit: number) => string | Out of the numeric range. |
minLength / maxLength | (label: string, limit: number, unit: 'characters' | 'items') => string | Out of the length range. |
field | string | Stands in for the name when an item has neither label nor prop. |
errorPrefix / warningPrefix | string | Read before an error or a warning; hidden on screen. |
validating | string | Shown when an async check runs past one second. |
optional | string | After optional labels when requiredMark="optional". |
summaryTitle | string | Default heading of TxFormErrorSummary. |
draftRestored / draftPending | (savedAt: Date) => string | The notice once a draft has filled the form in, or while it waits. |
draftRestore / draftDiscard | string | The notice's buttons. |
leaveConfirm | string | Asked through window.confirm when nothing else asks. |
autosaved / autosaveFailed | string | Read once an autosave went through, or when one failed and no message on screen says why; hidden on screen. |
CSS Variables
| Variable | Default | Description |
|---|---|---|
--tx-form-gap | 20px | Space between fields. |
--tx-form-label-max | 16em | Widest the side label column may grow; labelWidth writes it. |
--tx-form-control-height | 32px | Height of a one-line control, which labels line up with. |
--tx-form-item-min | 220px | Narrowest an item in a TxFormRow gets before the row wraps; 110px with condensed. |
Composables and host
useTxFormField
| Name | Type | Description |
|---|---|---|
useTxFormField | (kind?: 'input' | 'button' | 'group') => TxFormField | null | Connects a control to the item around it; kind decides how the label names the control. Returns null outside a form. |
id | string | undefined | Read-only; the id the label points at. Only the first control in an item receives one. |
labelId / label | string | undefined / string | Read-only; the id and text of the item's label. |
describedBy | string | undefined | Read-only; the ids of the message or help text and of the hint, space-separated. |
invalid / required | boolean | Read-only; an error is showing; the field is required. |
disabled / size | boolean / 'sm' | 'md' | 'lg' | Read-only; the form's disabled and size. |
readonly | boolean | Read-only; the form's readonly: the control takes focus but keeps its value. |
attrs | (host?: Record<string, unknown>) => Record<string, unknown> | The control's merged attributes; those the control was given win, except aria-describedby, which keeps both. |
provideTxFormHost
| Name | Type | Description |
|---|---|---|
provideTxFormHost | (host: TxFormHost, app?: App) => void | Gives the forms below — or, with app, in the whole app — what the host decides. Call it in a component's setup. Also exported from @talex-touch/tuffex/utils, which does not load the form. |
host.messages | MaybeRefOrGetter<Partial<FormMessages>> | Text in the host's language; a ref or getter follows locale switches. |
host.namespace | MaybeRefOrGetter<string | null> | Whose drafts these are, as user:42; null until that is known, and no draft is kept meanwhile. |
host.storage | FormDraftStorage | Where drafts go when persist.storage does not say. |
host.leaveConfirm | FormLeaveConfirm | Asks before leaving, for the forms without their own leaveConfirm. |
flushTxForms | () => Promise<void> | Writes every mounted form's pending draft, before the page goes without warning. |
clearTxFormDrafts | (options?: { namespace?: string | ((namespace: string) => boolean), storage?: FormDraftStorage }) => Promise<void> | Removes the drafts, one namespace's, or those of every namespace the function accepts. |
Drafts and Leaving
- A draft fills in only the fields the user has not touched; a field saved again since waits in the notice, or goes to
reconcilewithsource: 'draft'. - It is written 300ms after typing pauses, at least every 2 seconds while typing goes on, and as the page hides; a successful submit or
reset()deletes it. - Secrets stay out: password inputs,
TxSensitiveInput, inputs whoseautocompleteasks for a password, a one-time code or card details, items withpersistoff, andexcludepaths. A field that once held one stays out. - Reloading or closing the page asks first only while a change is in no draft: without
persist, in a secret field, or when a write has not landed. - A store that refuses a write keeps the draft in memory until one succeeds; a host namespace of
null, or a form withoutid, keeps no draft. - When the namespace changes to another, as on sign-out, edits left in the form go into no draft and count as unsaved until changed again;
clearTxFormDrafts({ namespace })removes that person's drafts.
Overview
- Validity updates as values change; a message appears once the user changes a field and leaves it (switching windows is not leaving), then follows each edit.
validate()and submit show every message. - Rules run in order and stop at the first error. Async rules run after the synchronous ones pass, debounce 300ms while typing, and show
messages.validatingpast one second. - Submit validates, then calls the handler; a handler that returns
false, throws, or callssetErrors()counts as a failure. On failure, focus moves to the error summary, or to the first field in error when there is none. - With
autosave, a pause of about a second saves the changes, checking only the changed fields; adisabledorreadonlyform does not autosave. Submit andconfirmLeave()save at once. - Controls are named by their label through
fororaria-labelledby, and messages are linked througharia-describedby; norole="alert"is set. - The
?beside a label is a plain button, named bymessages.hint; hover or keyboard focus shows thehinttext in a popover, Escape closes it, and the pointer can move into the panel.
Technologies
autoreads the form's own width through a container query; side layout shares the label column across items with CSS subgrid.schemadepends only on the Standard Schema v1 interface, not on a validation library.- Source:
packages/tuffex/packages/components/src/form/;useTxFormField, which the controls read, lives inpackages/tuffex/packages/utils/form-field.ts, so an on-demand import of a control does not pull the form in, andprovideTxFormHostinpackages/tuffex/packages/utils/form-host.ts, so an app can provide it at startup without loading the form.