Form
Group labeled fields, validate values and manage reset snapshots. HuiFormItem.prop connects each field to the form model, validation rules and reset operations.
Import
import { HuiForm, HuiFormItem, useFormItem } from '@nscode/handy-ui'
import type { FormRule, FormValidateResult } from '@nscode/handy-ui'
Basic validation
Rules are keyed by the exact field prop. validate() resolves a result even when validation fails; check its valid property. Reset restores the captured initial values rather than always assigning empty strings.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ name: '', email: '' })
const result = ref('Submit to validate')
const rules: Record<string, FormRule[]> = {
name: [{ required: true, message: 'Enter your name', trigger: 'blur' }],
email: [{ required: true, type: 'email', message: 'Enter a valid email', trigger: 'blur' }]
}
const submit = async () => {
const validation = await formRef.value!.validate()
result.value = validation.valid
? `Ready to save ${model.name}`
: JSON.stringify(validation.errors)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="90px">
<HuiFormItem label="Name" prop="name"><HuiInput v-model="model.name" /></HuiFormItem>
<HuiFormItem label="Email" prop="email"><HuiInput v-model="model.email" /></HuiFormItem>
<HuiFormItem
><HuiSpace
><HuiButton type="primary" @click="submit">Submit</HuiButton
><HuiButton @click="formRef?.resetFields()">Reset</HuiButton></HuiSpace
></HuiFormItem
>
</HuiForm>
<span>{{ result }}</span>
</HuiSpace>
</template>
Rules and asynchronous validators
Rules support required, type, min, max, pattern and validator. A missing trigger runs for blur, change and manual validation. An explicit trigger limits automatic validation; calling validate() without a trigger runs all rules. A validator may use a callback, return a boolean or return a Promise. The first result wins.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiForm,
HuiFormItem,
HuiInput,
HuiInputNumber,
HuiSpace
} from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ code: '', quantity: 1 })
const pending = ref(false)
const result = ref('The code taken is unavailable')
const rules: Record<string, FormRule[]> = {
code: [
{ required: true, min: 3, max: 12, message: 'Use 3–12 characters', trigger: 'blur' },
{ pattern: /^[a-z]+$/, message: 'Use lowercase letters', trigger: 'blur' },
{
validator: async (_rule, value) => {
await new Promise((resolve) => setTimeout(resolve, 500))
return value !== 'taken'
},
message: 'This code is unavailable',
trigger: 'blur'
}
],
quantity: [
{ type: 'number', min: 1, max: 20, message: 'Use a number from 1 to 20', trigger: 'change' }
]
}
const validate = async () => {
pending.value = true
try {
result.value = (await formRef.value!.validate()).valid
? 'Validation passed'
: 'Please correct the fields'
} finally {
pending.value = false
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="90px">
<HuiFormItem label="Code" prop="code"><HuiInput v-model="model.code" /></HuiFormItem>
<HuiFormItem label="Quantity" prop="quantity"
><HuiInputNumber v-model="model.quantity"
/></HuiFormItem>
</HuiForm>
<HuiSpace
><HuiButton :loading="pending" @click="validate">Validate</HuiButton
><span>{{ result }}</span></HuiSpace
>
</HuiSpace>
</template>
Labels and layout
Labels support left, right, top and float. label-width accepts a CSS width or pixels; auto aligns labels to the widest visible label. Inline forms can be used for compact rows. A label slot replaces label text and suffix.
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiForm, HuiFormItem, HuiInput, HuiSpace } from '@nscode/handy-ui'
import type { FormLabelPosition } from '@nscode/handy-ui'
const positions: FormLabelPosition[] = ['left', 'right', 'top', 'float']
const model = reactive({ name: '', note: '' })
</script>
<template>
<HuiSpace direction="vertical" fill>
<div v-for="position in positions" :key="position">
<p>{{ position }}</p>
<HuiForm :model="model" :label-position="position" label-width="auto" label-suffix=":">
<HuiFormItem label="Name" prop="name"><HuiInput v-model="model.name" /></HuiFormItem>
<HuiFormItem label="Additional note" prop="note"
><HuiInput v-model="model.note"
/></HuiFormItem>
</HuiForm>
</div>
<HuiForm :model="model" inline label-position="top">
<HuiFormItem prop="name"
><template #label><strong>Custom label</strong></template
><HuiInput v-model="model.name"
/></HuiFormItem>
<HuiFormItem label="Note" prop="note"><HuiInput v-model="model.note" /></HuiFormItem>
</HuiForm>
</HuiSpace>
</template>
Fixed columns and field spans
Set columns to a positive integer to enable a fixed grid. HuiFormItem.span specifies how many columns a field occupies. A span greater than the available columns is clamped to the current count. Switch between two and three columns below: span=2 remains two columns, while span=8 fills the available row.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace } from '@nscode/handy-ui'
const columns = ref(2)
const model = reactive({ name: '', email: '', address: '', notes: '', code: '', city: '' })
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="columns = 2">2 columns</HuiButton
><HuiButton @click="columns = 3">3 columns</HuiButton
><span>Current: {{ columns }}</span></HuiSpace
>
<HuiForm :model="model" :columns="columns" label-position="top">
<HuiFormItem label="Name · span 1" prop="name"><HuiInput v-model="model.name" /></HuiFormItem>
<HuiFormItem label="Email · span 1" prop="email"
><HuiInput v-model="model.email"
/></HuiFormItem>
<HuiFormItem label="Address · span 2" prop="address" :span="2"
><HuiInput v-model="model.address"
/></HuiFormItem>
<HuiFormItem label="Notes · span 8, clamped to available columns" prop="notes" :span="8"
><HuiInput v-model="model.notes"
/></HuiFormItem>
<HuiFormItem label="Code · span 1" prop="code"><HuiInput v-model="model.code" /></HuiFormItem>
<HuiFormItem label="City · span 1" prop="city"><HuiInput v-model="model.city" /></HuiFormItem>
</HuiForm>
</HuiSpace>
</template>
Automatic columns with a minimum width
itemMinWidth creates as many columns as the container can fit. Numbers use px; CSS lengths such as '14rem' are also accepted. Resize the container to see spans follow its actual nonzero grid tracks. A valid columns value takes priority when both layout props are supplied.
Only automatic columns subscribe to container-width changes. Ordinary and fixed-column forms do not register window resize listeners. Automatic mode uses ResizeObserver when available, otherwise a window resize fallback; leaving automatic mode removes that subscription.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace } from '@nscode/handy-ui'
const itemMinWidth = ref<number | string>(200)
const model = reactive({ name: '', code: '', address: '', notes: '' })
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="itemMinWidth = 200">200px</HuiButton
><HuiButton @click="itemMinWidth = '14rem'">14rem</HuiButton
><span>Minimum: {{ itemMinWidth }}</span></HuiSpace
>
<div class="resizable-form">
<HuiForm :model="model" :item-min-width="itemMinWidth" label-position="top">
<HuiFormItem label="Name" prop="name"><HuiInput v-model="model.name" /></HuiFormItem>
<HuiFormItem label="Code" prop="code"><HuiInput v-model="model.code" /></HuiFormItem>
<HuiFormItem label="Address · span 2" prop="address" :span="2"
><HuiInput v-model="model.address"
/></HuiFormItem>
<HuiFormItem label="Notes · span 8, clamped after measurement" prop="notes" :span="8"
><HuiInput v-model="model.notes"
/></HuiFormItem>
</HuiForm>
</div>
</HuiSpace>
</template>
<style scoped>
.resizable-form {
width: 100%;
min-width: 220px;
max-width: 100%;
resize: horizontal;
overflow: auto;
box-sizing: border-box;
padding: var(--hui-spacing-3);
border: var(--hui-border-width) solid var(--hui-border-color);
}
</style>
Grouped grid fields
HuiFormSection occupies a full row. Its fields use the form's fixed or automatic grid configuration. Automatic groups measure their own available width, so their spans do not use a wider outer container's column count.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiForm,
HuiFormItem,
HuiFormSection,
HuiInput,
HuiSpace
} from '@nscode/handy-ui'
const columns = ref(2)
const model = reactive({ name: '', phone: '', email: '', street: '', city: '', notes: '' })
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="columns = 2">2 columns</HuiButton
><HuiButton @click="columns = 3">3 columns</HuiButton></HuiSpace
>
<HuiForm :model="model" :columns="columns" label-position="top">
<HuiFormSection title="Contact details" collapsible>
<HuiFormItem label="Name" prop="name"><HuiInput v-model="model.name" /></HuiFormItem>
<HuiFormItem label="Phone" prop="phone"><HuiInput v-model="model.phone" /></HuiFormItem>
<HuiFormItem label="Email · span 2" prop="email" :span="2"
><HuiInput v-model="model.email"
/></HuiFormItem>
</HuiFormSection>
<HuiFormSection title="Delivery details">
<HuiFormItem label="Street · span 2" prop="street" :span="2"
><HuiInput v-model="model.street"
/></HuiFormItem>
<HuiFormItem label="City" prop="city"><HuiInput v-model="model.city" /></HuiFormItem>
<HuiFormItem label="Notes · span 8, full row" prop="notes" :span="8"
><HuiInput v-model="model.notes"
/></HuiFormItem>
</HuiFormSection>
</HuiForm>
</HuiSpace>
</template>
Readonly form
Set readonly on Form to make Input, Textarea, InputNumber, AutoComplete, Mentions, InputOtp, DatePicker, TimePicker, Rate and Checkbox (including CheckboxGroup) readonly while retaining focus and text selection. Other participating controls currently fall back to disabled. Buttons remain available.
Empty readonly fields still show their placeholders. Pagination page-size/jump controls and Tree's built-in search are browsing actions: they isolate Form, FormItem and inherited readonly contexts. They do not inherit form disabled/readonly, register as fields or trigger field validation. Pagination's own disabled prop still applies.
FormItem inherits this state; readonly=false on FormItem re-enables that field. A control's own readonly=false cannot override the form, while its readonly=true remains effective. Checkbox keeps its existing own-prop precedence over CheckboxGroup; form and field readonly still take priority.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiForm,
HuiFormItem,
HuiInput,
HuiTextarea,
HuiInputNumber,
HuiAutoComplete,
HuiMentions,
HuiInputOtp,
HuiDatePicker,
HuiTimePicker,
HuiRate,
HuiCheckbox,
HuiCheckboxGroup,
HuiSelect,
HuiSwitch,
HuiButton,
HuiSpace
} from '@nscode/handy-ui'
const readonly = ref(true)
const model = reactive({
name: 'Alex',
notes: 'Focus, select and copy text',
count: 3,
city: 'Beijing',
mention: '@Alex',
code: '123456',
date: '2026-11-19',
time: '09:30:00',
score: 4,
accepted: true,
choices: ['a'],
status: 'active',
enabled: true,
editable: 'This field remains editable'
})
const options = [
{ label: 'Active', value: 'active' },
{ label: 'Inactive', value: 'disabled' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="readonly = !readonly">Form readonly: {{ readonly }}</HuiButton>
<HuiForm :model="model" :readonly="readonly" :columns="2" label-position="top">
<HuiFormItem label="Input" required><HuiInput v-model="model.name" clearable /></HuiFormItem>
<HuiFormItem label="Textarea"><HuiTextarea v-model="model.notes" /></HuiFormItem>
<HuiFormItem label="InputNumber"><HuiInputNumber v-model="model.count" /></HuiFormItem>
<HuiFormItem label="AutoComplete"
><HuiAutoComplete v-model="model.city" :suggestions="['Beijing', 'Shanghai']"
/></HuiFormItem>
<HuiFormItem label="Mentions"
><HuiMentions v-model="model.mention" :options="[{ label: 'Alex', value: 'Alex' }]"
/></HuiFormItem>
<HuiFormItem label="InputOtp"><HuiInputOtp v-model="model.code" /></HuiFormItem>
<HuiFormItem label="DatePicker"
><HuiDatePicker v-model="model.date" value-format="YYYY-MM-DD"
/></HuiFormItem>
<HuiFormItem label="TimePicker"><HuiTimePicker v-model="model.time" /></HuiFormItem>
<HuiFormItem label="Rate"><HuiRate v-model="model.score" /></HuiFormItem>
<HuiFormItem label="Checkbox"
><HuiCheckbox v-model="model.accepted">Agree</HuiCheckbox></HuiFormItem
>
<HuiFormItem label="CheckboxGroup"
><HuiCheckboxGroup v-model="model.choices"
><HuiCheckbox value="a">A</HuiCheckbox
><HuiCheckbox value="b">B</HuiCheckbox></HuiCheckboxGroup
></HuiFormItem
>
<HuiFormItem label="Select (disabled fallback)"
><HuiSelect v-model="model.status" :options="options"
/></HuiFormItem>
<HuiFormItem label="Switch (disabled fallback)"
><HuiSwitch v-model="model.enabled"
/></HuiFormItem>
<HuiFormItem label="FormItem readonly=false" :readonly="false"
><HuiInput v-model="model.editable"
/></HuiFormItem>
</HuiForm>
<span
>Editable field: {{ model.editable }}; number: {{ model.count }}; rating:
{{ model.score }}</span
>
</HuiSpace>
</template>
Readonly fields hide required markers and skip blur validation. If a field already has an error, programmatic value changes recheck all rules, including blur-only rules, and clear the old error when valid. Changes without an existing error do not create new errors. validateEvent=false disables this automatic recheck; manual validate()/validateField() remain available. Resetting snapshots does not recheck. Switching to readonly closes open suggestion/date/time panels and invalidates pending suggestion requests. Validate manually, then fill a valid name to observe the old error disappearing:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ name: '', remark: 'Readonly notes' })
const rules: Record<string, FormRule[]> = {
name: [{ required: true, message: 'Name is required', trigger: 'blur' }]
}
const result = ref('Validate manually, then fill the name programmatically')
const validate = async () => {
const value = await formRef.value!.validate()
result.value = value.valid ? 'Valid' : JSON.stringify(value.errors)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm ref="formRef" :model="model" :rules="rules" readonly>
<HuiFormItem label="Name" prop="name"
><HuiInput v-model="model.name" :readonly="false"
/></HuiFormItem>
<HuiFormItem label="Notes" prop="remark"><HuiInput v-model="model.remark" /></HuiFormItem>
</HuiForm>
<HuiButton @click="validate">Manual validate()</HuiButton>
<HuiButton
@click="
model.name = 'Fetched name'
result = 'Filled; existing errors recheck all rules'
"
>Fill a valid name</HuiButton
>
<HuiButton
@click="
model.name = ''
result = 'Empty; changes without existing errors create no new error'
"
>Fill an empty value</HuiButton
>
<span>{{ result }}</span>
</HuiSpace>
</template>
Size and disabled state
Size precedence is control, FormItem, Form, ConfigProvider, then default. Disabling a form disables its participating controls, including a control with disabled=false. Buttons do not inherit the form's disabled state or size.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiForm, HuiFormItem, HuiInput, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { FormSize } from '@nscode/handy-ui'
const sizes: FormSize[] = ['large', 'default', 'small']
const disabled = ref(false)
const model = reactive({ name: 'Alex' })
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace><span>Disable forms</span><HuiSwitch v-model="disabled" /></HuiSpace>
<HuiForm v-for="size in sizes" :key="size" :model="model" :size="size" :disabled="disabled">
<HuiFormItem :label="size" prop="name"
><HuiInput v-model="model.name" :disabled="false"
/></HuiFormItem>
</HuiForm>
</HuiSpace>
</template>
Error placement and field validation events
bottom places messages below controls; inside places them inside supported single-line controls and falls back to bottom for unsupported or compound controls. show-message controls message visibility. required markers can be hidden independently.
Controls register the actual container with useFormItem().registerInsideTarget(el); component class names do not determine support. Custom controls must register again when their element ref changes and arrange their internal layout for the message. Replacing the target or unmounting releases the old registration. Only one outermost registered target within the item's content receives the message; multiple independent targets, unsupported controls and nested items keep their fallback or isolation. SSR does not read the DOM and renders the error below the control.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ first: '', second: '' })
const show = ref(true)
const hideMarker = ref(false)
const event = ref('No validation yet')
const onValidate = (prop: string, valid: boolean, error?: string) => {
event.value = `${prop}: ${valid ? 'valid' : error}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><span>Show messages</span><HuiSwitch v-model="show" /><span>Hide required marker</span
><HuiSwitch v-model="hideMarker"
/></HuiSpace>
<HuiForm
ref="formRef"
:model="model"
:show-message="show"
:hide-required-asterisk="hideMarker"
@validate="onValidate"
>
<HuiFormItem label="bottom" prop="first" required error-placement="bottom"
><HuiInput v-model="model.first"
/></HuiFormItem>
<HuiFormItem label="inside" prop="second" required error-placement="inside"
><HuiInput v-model="model.second"
/></HuiFormItem>
</HuiForm>
<HuiSpace
><HuiButton @click="formRef?.validate()">Validate</HuiButton
><span>{{ event }}</span></HuiSpace
>
</HuiSpace>
</template>
Server field errors
External value watching exists only while an assigned error is present and stops when it clears. With scrollToError enabled, setErrors() scrolls to the first field receiving a nonempty error in this call, in form order; old errors and cleared entries do not choose the target.
setErrors(errors) matches each key exactly against FormItem.prop. Arrays use their first message. An empty string, undefined or an empty array clears that field. Unlisted fields are unchanged; unmatched keys produce a development warning. Dot and bracket paths are not normalized for matching: items.0.qty and items[0].qty are different keys.
An external error is cleared when that field's value changes, even without a change rule. The next validation, clearValidate() and resetFields() also clear it. setErrors and FormItem.setError do not emit validation events, and a pending older validation cannot overwrite a newly assigned error. A nonempty error prop remains the highest-priority displayed text.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiForm,
HuiFormItem,
HuiInput,
HuiInputNumber,
HuiSpace
} from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ name: 'Alex', items: [{ qty: 1 }] })
const state = ref('Click Apply server errors, then edit a field')
const apply = () => {
formRef.value!.setErrors({
name: ['This name is already used', 'This second message stays hidden'],
'items[0].qty': 'Quantity is unavailable'
})
state.value = 'First array message shown; editing clears each external error'
}
const clear = () => {
formRef.value!.setErrors({ name: '', 'items[0].qty': undefined })
state.value = 'The named errors were cleared'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm ref="formRef" scroll-to-error :model="model" label-width="90px">
<HuiFormItem label="Name" prop="name"><HuiInput v-model="model.name" /></HuiFormItem>
<HuiFormItem label="Quantity" prop="items[0].qty"
><HuiInputNumber v-model="model.items[0].qty"
/></HuiFormItem>
</HuiForm>
<HuiSpace
><HuiButton @click="apply">Apply server errors</HuiButton
><HuiButton @click="clear">Clear named errors</HuiButton></HuiSpace
>
<span>{{ state }}</span>
</HuiSpace>
</template>
Capture values after asynchronous loading
After assigning fetched values, wait for nextTick(), call setInitialValues() to capture the current values, then call clearValidate() separately if needed. Capturing a snapshot does not modify the model or validation state. Reset will subsequently return to the fetched values.
<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ name: '', profile: { city: '' } })
const loading = ref(false)
const status = ref('Load a record, edit it, then reset')
const load = async () => {
loading.value = true
try {
await new Promise((resolve) => setTimeout(resolve, 400))
Object.assign(model, { name: 'Loaded customer', profile: { city: 'London' } })
await nextTick()
formRef.value!.setInitialValues()
formRef.value!.clearValidate()
status.value = 'Fetched values are now the reset snapshot'
} finally {
loading.value = false
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton :loading="loading" @click="load">Load record</HuiButton
><HuiButton :disabled="loading" @click="formRef?.resetFields()"
>Reset to captured values</HuiButton
></HuiSpace
>
<HuiForm ref="formRef" :model="model" label-width="90px">
<HuiFormItem label="Name" prop="name"><HuiInput v-model="model.name" /></HuiFormItem>
<HuiFormItem label="City" prop="profile.city"
><HuiInput v-model="model.profile.city"
/></HuiFormItem>
</HuiForm>
<span>{{ status }}; current: {{ model.name }} / {{ model.profile.city }}</span>
</HuiSpace>
</template>
Explicit initial values and undefined
setInitialValues(values) reads each registered prop from the supplied object and deep-copies the snapshot, without changing current values. The method distinguishes no argument from one explicit undefined argument: setInitialValues() captures current values; setInitialValues(undefined) makes registered reset values undefined.
Fields mounted later still capture their own values at mount time. A snapshot only affects fields already registered; it does not prescribe defaults for future fields.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive<{ name: string | undefined }>({ name: 'Current value' })
const status = ref('A snapshot does not immediately change the input')
const preset = () => {
formRef.value!.setInitialValues({ name: 'Preset reset value' })
status.value = 'Preset captured; the input is unchanged until reset'
}
const empty = () => {
formRef.value!.setInitialValues(undefined)
status.value = 'Reset will now assign undefined'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm ref="formRef" :model="model"
><HuiFormItem label="Name" prop="name"><HuiInput v-model="model.name" /></HuiFormItem
></HuiForm>
<HuiSpace wrap
><HuiButton @click="preset">Capture supplied values</HuiButton
><HuiButton @click="formRef?.setInitialValues()">Capture current value</HuiButton
><HuiButton @click="empty">Capture undefined</HuiButton
><HuiButton @click="formRef?.resetFields()">Reset</HuiButton></HuiSpace
>
<span>{{ status }}; current: {{ model.name ?? '(undefined)' }}</span>
</HuiSpace>
</template>
Individual FormItem methods
Use a FormItem ref to set an error or a reset snapshot for one field. setInitialValue() reads the current field, whereas setInitialValue(undefined) records an undefined reset value. These methods do not change current data or run validation. Use resetField() to apply the snapshot.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiInput, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const itemRef = ref<InstanceType<typeof HuiFormItem>>()
const model = reactive<{ name: string | undefined }>({ name: 'Original' })
const forceError = ref(false)
const status = ref('Edit the value and capture it')
const capture = () => {
itemRef.value!.setInitialValue()
status.value = 'Current field value captured'
}
const captureUndefined = () => {
itemRef.value!.setInitialValue(undefined)
status.value = 'Undefined captured'
}
const reset = async () => {
await itemRef.value!.resetField()
status.value = `Reset result: ${model.name ?? '(undefined)'}`
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace><span>Use explicit error prop</span><HuiSwitch v-model="forceError" /></HuiSpace>
<HuiForm :model="model">
<HuiFormItem
ref="itemRef"
label="Name"
prop="name"
:error="forceError ? 'Explicit error prop takes priority' : undefined"
><HuiInput v-model="model.name"
/></HuiFormItem>
</HuiForm>
<HuiSpace wrap
><HuiButton @click="itemRef?.setError('Field API error')">setError</HuiButton
><HuiButton @click="itemRef?.setError()">Clear API error</HuiButton
><HuiButton @click="capture">setInitialValue()</HuiButton
><HuiButton @click="captureUndefined">setInitialValue(undefined)</HuiButton
><HuiButton @click="reset">resetField()</HuiButton></HuiSpace
>
<span>{{ status }}</span>
</HuiSpace>
</template>
Dirty state and reset baseline
isDirty() compares registered fields with their reset snapshots. Pass one exact field path or an array to limit the check. It works in templates and computed values. Arrays, ordinary objects and Dates compare by value; Files, Blobs and class instances compare by original reference. Fields mounted later capture their own mount-time values.
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { HuiForm, HuiFormItem, HuiInput, HuiButton, HuiSpace } from '@nscode/handy-ui'
const form = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ user: { name: 'Original' }, remark: '' })
const dirty = computed(() => form.value?.isDirty() ?? false)
const capture = () => form.value?.setInitialValues()
const reset = () => form.value?.resetFields()
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm ref="form" :model="model" label-position="top">
<HuiFormItem label="Name" prop="user.name"
><HuiInput v-model="model.user.name"
/></HuiFormItem>
<HuiFormItem label="Remark" prop="remark"><HuiInput v-model="model.remark" /></HuiFormItem>
</HuiForm>
<HuiSpace>
<HuiButton :disabled="!dirty" @click="capture">Capture current defaults</HuiButton>
<HuiButton @click="reset">Reset</HuiButton>
</HuiSpace>
<p>Any changes: {{ dirty }}; name changed: {{ form?.isDirty('user.name') ?? false }}</p>
</HuiSpace>
</template>
Persistent field descriptions
The tip slot overrides the prop. Descriptions remain below the control when an error appears or showMessage is false. Bottom errors follow the description; inside errors stay inside the control. Automatically generated aria-describedby includes both the description and visible error IDs.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiForm, HuiFormItem, HuiInput, HuiButton, HuiSpace } from '@nscode/handy-ui'
const model = reactive({ code: '', name: '' })
const showError = ref(true)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="showError = !showError">Show errors: {{ showError }}</HuiButton>
<HuiForm :model="model" :show-message="showError" label-position="top">
<HuiFormItem
label="Code"
prop="code"
tip="Cannot be changed after saving"
error="Enter a code"
>
<HuiInput v-model="model.code" />
</HuiFormItem>
<HuiFormItem
label="Name"
prop="name"
tip="Overridden"
error="Name already exists"
error-placement="inside"
>
<HuiInput v-model="model.name" />
<template #tip>Supports <strong>rich text</strong>; errors remain visible.</template>
</HuiFormItem>
</HuiForm>
</HuiSpace>
</template>
Dependencies, debounce and validated submission
dependencies revalidates a field after it has produced a validation result. It runs all rules. validateDebounce delays change validation only, and the delay counts towards isValidating(). Blur, dependency revalidation, manual validation and submission run immediately. Validators receive the model, exact field path, label, trigger and AbortSignal as a fourth argument.
submit-success means validation passed; save data in that callback. It does not mean a business request succeeded. Native submit buttons and submit() use the same event chain. Automatic validation only runs when a submit-success or submit-failed listener exists. Existing native @submit.prevent handlers continue to work.
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiForm, HuiFormItem, HuiInput, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { FormRule, FormValidateResult } from '@nscode/handy-ui'
const form = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ password: '', confirm: '', code: '' })
const result = ref('Validate confirmation, then change the original password.')
const rules: Record<string, FormRule[]> = {
password: [{ required: true, message: 'Enter a password' }],
confirm: [
{
trigger: 'blur',
message: 'Passwords differ',
validator: (_rule, value, _callback, context) => value === context.model?.password
}
],
code: [
{
required: true,
message: 'Code is required and cannot be taken',
validator: async (_rule, value, _callback, { signal }) => {
await new Promise<void>((resolve, reject) => {
const abort = () => {
clearTimeout(timer)
reject(new Error('Cancelled'))
}
const timer = setTimeout(() => {
signal.removeEventListener('abort', abort)
resolve()
}, 300)
signal.addEventListener('abort', abort, { once: true })
})
return value !== 'taken'
}
}
]
}
const success = () => {
result.value = 'Validation passed; ready to save.'
}
const failed = (validation: FormValidateResult) => {
result.value = Object.values(validation.errors).flat().join('; ')
}
const validateConfirm = async () => {
await form.value?.validateField('confirm')
}
const submit = () => {
form.value?.submit()
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm
ref="form"
:model="model"
:rules="rules"
label-position="top"
@submit-success="success"
@submit-failed="failed"
>
<HuiFormItem label="Password" prop="password"
><HuiInput v-model="model.password"
/></HuiFormItem>
<HuiFormItem label="Confirm" prop="confirm" :dependencies="['password']">
<HuiInput v-model="model.confirm" />
</HuiFormItem>
<HuiFormItem
label="Code"
prop="code"
:validate-debounce="200"
tip="Try taken to see an error"
>
<HuiInput v-model="model.code" />
</HuiFormItem>
<HuiButton native-type="submit" type="primary" :loading="form?.isValidating()"
>Validate and submit</HuiButton
>
</HuiForm>
<HuiSpace>
<HuiButton @click="validateConfirm">Validate confirmation</HuiButton>
<HuiButton @click="submit">Call submit()</HuiButton>
</HuiSpace>
<p aria-live="polite">Validating: {{ form?.isValidating() ?? false }}; {{ result }}</p>
</HuiSpace>
</template>
HuiForm Props
| Prop | Type | Default | Description |
|---|---|---|---|
| model | Record<string, unknown> | — | Object read by validation and written by reset |
| rules | Record<string, FormRule[]> | — | Rules keyed by exact field prop |
| inline | boolean | false | Inline layout |
| columns | number | — | Fixed positive integer column count; takes priority over itemMinWidth |
| itemMinWidth | number | string | — | Automatic minimum column width; numbers use px, strings use CSS lengths |
| labelPosition | 'left' | 'right' | 'top' | 'float' | 'right' | Label placement |
| labelWidth | string | number | '80px' | Width; numbers are pixels, auto aligns to the widest label |
| labelSuffix | string | '' | Text appended to ordinary labels |
| hideRequiredAsterisk | boolean | false | Hide required markers |
| showMessage | boolean | true | Show validation messages |
| errorPlacement | 'bottom' | 'inside' | 'bottom' | Validation message placement |
| size | 'large' | 'default' | 'small' | ConfigProvider or default | Field and control size |
| readonly | boolean | false | Whole-form readonly; unsupported controls fall back to disabled |
| disabled | boolean | false | Disable participating controls |
| scrollToError | boolean | false | Scroll after validation failure or to the first field receiving a nonempty setErrors error |
HuiFormItem Props
| Prop | Type | Default | Description |
|---|---|---|---|
| prop | string | — | Model path such as user.name, items[0].qty or items.0.qty |
| span | number | — | Positive integer grid span in Form or SearchForm; clamped to measured available columns |
| label | string | — | Label and source for labeled validation messages |
| tip | string | — | Persistent description below the control; tip slot takes priority |
| labelWidth | number | string | Form value | Override label width; auto uses this label's natural width |
| labelPosition | 'left' | 'right' | 'top' | 'float' | Form value | Override label placement |
| required | boolean | Rule-derived | Override the required setting in merged rules |
| rules | FormRule[] | — | Additional rules for this field |
| dependencies | string[] | — | Revalidate after dependent paths change, once this field has a result |
| validateDebounce | number | 0 | Delay change validation in milliseconds; other validation runs immediately |
| error | string | — | Explicit error text, taking display priority over API and rule errors |
| showMessage | boolean | Form value | Override message visibility |
| errorPlacement | 'bottom' | 'inside' | Form value | Override error placement |
| readonly | boolean | undefined | Inherit form; false re-enables this field |
| size | 'large' | 'default' | 'small' | Form value | Override this field's control size |
Events
| Component | Event | Parameters | Description |
|---|---|---|---|
| HuiForm | validate | (prop: string, valid: boolean, error?: string) | A field completed rule validation |
| HuiForm | submit | (event: SubmitEvent) | Native submit event; page navigation is prevented |
| HuiForm | submit-success | (model: Record<string, unknown> | undefined, event: SubmitEvent) | Submission validation passed; not business save completion |
| HuiForm | submit-failed | (result: FormValidateResult, event: SubmitEvent) | Submission validation failed; respects scrollToError |
| HuiFormItem | validate | (valid: boolean, error?: string) | This field completed rule validation |
Slots
| Component | Slot | Description |
|---|---|---|
| HuiForm | default | FormItem components |
| HuiFormItem | default | Field control |
| HuiFormItem | label | Replace the ordinary label and suffix |
| HuiFormItem | tip | Persistent description; overrides the tip prop |
HuiForm methods
| Method | Signature | Description |
|---|---|---|
| validate | (callback?: FormValidateCallback) => Promise<FormValidateResult> | Validate every registered field |
| validateField | (props: string | string[], callback?: FormValidateCallback) => Promise<FormValidateResult> | Validate named fields |
| resetFields | (props?: string | string[]) => void | Restore snapshots and clear validation |
| clearValidate | (props?: string | string[]) => void | Clear validation without modifying the model |
| scrollToField | (prop: string) => void | Scroll to a field without validating |
| setErrors | (errors: Record<string, string | string[] | undefined>) => void | Set or clear errors for exact registered props |
| setInitialValues | (...values: [Record<string, unknown>?]) => void | Capture current values with no argument, or read supplied values; explicit undefined is distinct |
| isDirty | (props?: string | string[]) => boolean | Compare registered fields with reset snapshots, reactively |
| isValidating | (props?: string | string[]) => boolean | Check pending debounce or asynchronous validation |
| submit | () => void | Dispatch native submission; validate when validated-submit listeners exist |
HuiFormItem methods
| Method | Signature | Description |
|---|---|---|
| validate | (trigger?: 'blur' | 'change') => Promise<FormItemValidateResult> | Validate this field; optionally filter rules by trigger |
| resetField | () => Promise<void> | Apply this field's initial snapshot and clear validation |
| clearValidation | () => void | Clear validation without changing the value |
| setError | (message?: string) => void | Set an API error, or clear it with empty/undefined; no validate event |
| setInitialValue | (...values: [unknown?]) => void | Capture current value with no argument, or use the supplied value including explicit undefined |
Custom control integration
useFormItem(options) merges size and disabled state, connects controls with their label and error ARIA attributes, and triggers validation when the supplied value getter changes.
| Option | Description |
|---|---|
| readonly | Own readonly state; false cannot override a readonly form |
| supportsReadonly | true when the control handles readonly interaction; otherwise disabled fallback applies |
| disabled, size | Own control state, optionally supplied as refs or getters |
| value | Getter used to trigger change validation |
| deep | Observe in-place changes to arrays or objects |
| validateEvent | Disable automatic validation when false |
| labelable | false for controls whose root uses a role instead of a native labelable input |
| id | Explicit control ID, optionally supplied as a ref or getter |
The return value contains formDisabled (including disabled fallback), formReadonly, formSize, validate(trigger), inputAttrs for a native input, fieldAttrs for a role-bearing root, and the form/formItem contexts.
validate(trigger) skips readonly blur validation and only rechecks a readonly field on change when it already has an error. That recheck runs all rules. validateEvent=false disables automatic validation.
Types
import type {
FormProps,
FormItemProps,
FormRule,
FormSize,
FormLabelPosition,
FormErrorPlacement,
FormValidateTrigger,
FormValidatorContext,
FormValidateResult,
FormItemValidateResult,
FormValidateCallback,
FormContext,
FormItemContext,
UseFormItemOptions
} from '@nscode/handy-ui'
interface FormValidateResult {
valid: boolean
errors: Record<string, string[]>
}
interface FormItemValidateResult {
valid: boolean
error?: string
}
type FormValidateCallback = (valid: boolean, errors?: Record<string, string[]>) => void
interface FormValidatorContext {
model: Record<string, unknown> | undefined
prop: string
label?: string
trigger?: FormValidateTrigger
signal: AbortSignal
}
// FormRule.validator preserves its first three arguments and adds context:
// (rule, value, callback, context) => void | boolean | Promise<unknown>