Form

A form container with layouts, validation and submit state.

VerifiedSince 0.3.4

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.

Loading demo...

Layout

auto puts labels beside the fields once the form is 520px wide, and above them when it is narrower.

Loading demo...

Field Hints

The ? beside a label shows the full explanation on hover or focus; help stays under the control as one short constraint.

Loading demo...

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.

Loading demo...

Async Validation

An async validator runs after the synchronous rules pass, debounces while the user types, and aborts when the value moves on.

Loading demo...

Submit and Server Errors

@submit runs once every check passes; setErrors() inside the handler hands server errors back to their fields.

Loading demo...

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 demo...

Loading and Merging Data

setBaseline() loads fetched data; fields the user changed are kept unless reconcile decides otherwise.

Loading demo...

Drafts

persist keeps what the user typed under the form's id, so a reload or a closed tab brings it back.

Loading demo...

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".

Loading demo...

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.

Loading demo...

Long Questionnaires

validate-on="submit" lets people answer uninterrupted, and on submit TxFormErrorSummary lists every problem, each linking to its field.

Loading demo...

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, and anon when signed out; give null while 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 persist off 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 model the 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 into model, so dirty and reset() measure against it.
  • Put shared rules in form-level rules; an item's rules replace 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; help takes 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 pass signal to its request.
  • Turn persist on once the record has loaded, so the draft is laid over the saved values rather than empty ones.

API Reference

TxForm

Props

PropTypeDefaultDescription
idstringgeneratedThe <form> element's id, and the prefix of every field id: <id>-<prop>.
modelRecord<string, any>-Reactive form data; items read their field by the prop path.
rulesFormRules-Form-level rules keyed by field path.
schemaFormStandardSchema-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".
labelWidthstring | number16emWidest 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.
messagesPartial<FormMessages>-Overrides the built-in text.
size'small' | 'medium' | 'large''medium'Passed to the controls inside that have sizes.
disabledbooleanfalseDisables every control inside that reads the form, and blocks submit.
readonlybooleanfalseShows 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.
reconcileFormReconcile-Decides what model holds when setBaseline() or a draft brings values for fields the user changed.
persistboolean | FormPersistOptionsfalseKeeps what the user typed under id; true takes the defaults.
leaveConfirmFormLeaveConfirm | falsehost's, then window.confirmAsked before leaving with changes no draft holds; false never asks, as for a filter.
autosaveboolean | FormAutosaveOptionsfalseSaves 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

EventPayloadDescription
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

SlotPropsDescription
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

NameTypeDescription
dirtybooleanRead-only; model differs from the baseline.
validbooleanRead-only; no error blocks submit, whether or not it shows yet.
submittingbooleanRead-only; the submit handler is running.
submittedbooleanRead-only; the form has been submitted at least once; reset() clears it.
errorsRecord<string, string>Read-only; the errors showing, by field path.
rootErrorstringRead-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() => voidRestores model to the baseline and clears every message.
resetFields() => voidOlder name of reset().
setBaseline(values?: FormValues) => voidMakes fetched values the baseline; without them, the current model becomes the baseline.
setErrors(errors: Record<string, string | null | undefined>, options?: { source?: 'server' | 'client' }) => voidShows 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) => voidSets or clears the form-level error.
clearValidate(paths?: string | string[]) => voidHides messages without changing model.
draftFormDraftStateRead-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

PropTypeDefaultDescription
labelstring''Label text; no label renders without it.
propstring-The field's path in model: name, meta.homepage, links[0].url.
rulesFormRule | FormRule[]-Rules for this field; they replace the form-level rules for the same path.
requiredbooleanfalseShows the required marker and adds a required rule.
helpstring-Helper text under the control; an error or warning takes its place while it shows.
hintstring-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.
showMessagebooleantrueShows the message under the control; with it off, the control is still marked invalid.
inlinebooleanfalseCentres the label on the control; in a stacked layout, puts it beside the control.
persistbooleantruefalse keeps the field out of the draft, as a secret is.

Events

EventPayloadDescription
validate(valid: boolean)Fires after this field validates: on leaving it changed, or when the form validates.

Slots

SlotPropsDescription
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

PropTypeDefaultDescription
labelstring''Names the row as a group; in side layout it sits in the label column.
condensedbooleanfalseLets each item shrink to 110px instead of 220px before the row wraps.

Slots

SlotPropsDescription
default-The row's TxFormItems, with their labels above.

TxFormErrorSummary

Props

PropTypeDefaultDescription
titlestringmessages.summaryTitleThe summary's heading.

Types

FormRule, one entry of rules:

FieldTypeDescription
requiredbooleanRejects empty values.
type'email' | 'url' | 'number' | 'integer'The value's format.
min / maxnumberNumeric range.
minLength / maxLengthnumberCharacters in a string, or items in an array.
patternRegExpA pattern the value must match.
messagestringMessage when this rule fails, replacing the built-in text.
level'error' | 'warning'warning shows its message but never blocks submit.
depsstring[]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:

FieldTypeDescription
source'baseline' | 'draft'baseline is setBaseline(); draft is a stored draft whose fields were saved again since.
incomingFormValuesThe values arriving; they become the new baseline whatever model ends up holding.
currentFormValuesmodel as the user left it.
baselineFormValuesThe baseline the user's edits were made against.
dirtyPathsstring[]Paths the user changed that incoming also carries.
mergedFormValuesThe default, taken when nothing is returned: incoming with dirtyPaths kept, or for a draft, model as it is.
originFormValuesFor a draft: the saved values its edits were made against, for a three-way merge.

FormPersistOptions, the object form of persist:

FieldTypeDescription
recordIdstring | numberKeeps each record's draft apart: 42 for /posts/42/edit.
namespacestringWhose drafts these are; defaults to the host's, then default.
versionnumberBump it when the model's shape changes; a draft from another version is dropped. Default 1.
ttlnumber | '7d' | '12h' | '30m'How long a draft lasts after its last write, in milliseconds or units. Default '7d'.
storage'local' | 'session' | 'memory' | FormDraftAdapterDefaults to the host's, then local; memory lasts until the page reloads.
excludestring[]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:

FieldTypeDescription
get / remove(key: string) => string | null / (key: string) => voidReads or deletes one draft.
set(key: string, value: string) => voidThrow when the value was not stored; the form keeps it in memory meanwhile.
clear(prefix: string) => voidOptional; 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:

FieldTypeDescription
delaynumberHow long editing pauses before the changes are saved, in milliseconds. Default 1000.

FormMessages, the built-in text; the English defaults are FORM_DEFAULT_MESSAGES:

FieldTypeDescription
required / invalid / pattern(label: string) => stringMissing value, failed validator, mismatched pattern.
hint(label: string) => stringThe accessible name of the ? button beside a label.
type(label: string, type: FormRuleType) => stringWrong type.
min / max(label: string, limit: number) => stringOut of the numeric range.
minLength / maxLength(label: string, limit: number, unit: 'characters' | 'items') => stringOut of the length range.
fieldstringStands in for the name when an item has neither label nor prop.
errorPrefix / warningPrefixstringRead before an error or a warning; hidden on screen.
validatingstringShown when an async check runs past one second.
optionalstringAfter optional labels when requiredMark="optional".
summaryTitlestringDefault heading of TxFormErrorSummary.
draftRestored / draftPending(savedAt: Date) => stringThe notice once a draft has filled the form in, or while it waits.
draftRestore / draftDiscardstringThe notice's buttons.
leaveConfirmstringAsked through window.confirm when nothing else asks.
autosaved / autosaveFailedstringRead once an autosave went through, or when one failed and no message on screen says why; hidden on screen.

CSS Variables

VariableDefaultDescription
--tx-form-gap20pxSpace between fields.
--tx-form-label-max16emWidest the side label column may grow; labelWidth writes it.
--tx-form-control-height32pxHeight of a one-line control, which labels line up with.
--tx-form-item-min220pxNarrowest an item in a TxFormRow gets before the row wraps; 110px with condensed.

Composables and host

useTxFormField

NameTypeDescription
useTxFormField(kind?: 'input' | 'button' | 'group') => TxFormField | nullConnects a control to the item around it; kind decides how the label names the control. Returns null outside a form.
idstring | undefinedRead-only; the id the label points at. Only the first control in an item receives one.
labelId / labelstring | undefined / stringRead-only; the id and text of the item's label.
describedBystring | undefinedRead-only; the ids of the message or help text and of the hint, space-separated.
invalid / requiredbooleanRead-only; an error is showing; the field is required.
disabled / sizeboolean / 'sm' | 'md' | 'lg'Read-only; the form's disabled and size.
readonlybooleanRead-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

NameTypeDescription
provideTxFormHost(host: TxFormHost, app?: App) => voidGives 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.messagesMaybeRefOrGetter<Partial<FormMessages>>Text in the host's language; a ref or getter follows locale switches.
host.namespaceMaybeRefOrGetter<string | null>Whose drafts these are, as user:42; null until that is known, and no draft is kept meanwhile.
host.storageFormDraftStorageWhere drafts go when persist.storage does not say.
host.leaveConfirmFormLeaveConfirmAsks 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 reconcile with source: '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 whose autocomplete asks for a password, a one-time code or card details, items with persist off, and exclude paths. 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 without id, 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.validating past one second.
  • Submit validates, then calls the handler; a handler that returns false, throws, or calls setErrors() 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; a disabled or readonly form does not autosave. Submit and confirmLeave() save at once.
  • Controls are named by their label through for or aria-labelledby, and messages are linked through aria-describedby; no role="alert" is set.
  • The ? beside a label is a plain button, named by messages.hint; hover or keyboard focus shows the hint text in a popover, Escape closes it, and the pointer can move into the panel.

Technologies

  • auto reads the form's own width through a container query; side layout shares the label column across items with CSS subgrid.
  • schema depends 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 in packages/tuffex/packages/utils/form-field.ts, so an on-demand import of a control does not pull the form in, and provideTxFormHost in packages/tuffex/packages/utils/form-host.ts, so an app can provide it at startup without loading the form.
查看源码
packages/tuffex/packages/components/src/form/index.ts