Form
Forms: typed model, rules, dependent fields, asynchronous validations and submission.
When to use
Form is needed when several fields form one task: registration, editing a record, searching or filling out an application. The model stores values and errors, rules validate input, and dispatch receives a consistent set of data.
In @woodger/antd, create a model with Form.useForm() or createForm. Form connects the model to a native form, and Form.Item provides the field label, errors, and accessible description.
For one independent switch or filter, you can use the Svelte local state. Connect Form when you need general validation, sending and resetting of several fields.
Form CSS prefixes show global ConfigProvider.prefixCls and local prefixCls without resetting state. Form and FormItem choose prefixes independently. FormList.prefixCls refers to the ErrorList, not the adjacent fields. Adaptive captions respect the screen*max design tokens of their topic area; changing the prefix preserves the model and rules.
Model and connection with fields
Call Form.useForm<Values>() during component initialization. The hook returns a one-element tuple and can reuse an existing model. Pass the model to Form with form. When form is omitted, the component creates its own model. initialValues provides defaults for fields that mount later as well.
| Part of the form | Responsibility | Working example |
|---|---|---|
createForm |
Meanings, Rules, Errors and Methods | Model methods |
Form |
Send, reset, design and context | Regular form |
FormItem |
Field name, label, error and tooltip | Regular form |
| Control | Input and change message | Own control |
form.values is available for reading and reactive computing. To record, use setFieldValue, setFieldsValue, or batch setFields. Do not assign properties to values directly or bind them through bind:value: the model must receive changes through its methods.
A named Form.Item supplies the label and field metadata to supported controls. Connect the value through the control snippet or pass it explicitly. To manage Input, InputNumber, or Select explicitly, pass value and call form.setFieldValue from onValueChange. For Switch and Checkbox, use checked and onCheckedChange. The checked field example shows the explicit connection.
The model stores scalars, nested objects, arrays, and instances of classes, including Dayjs. Objects and arrays are copied on set and reset; class instances are saved without serialization. The limits of the available API are listed in Form directory.
Layout and captions
Form.layout supports vertical, horizontal and inline; default Svelte - vertical. FormItem.layout can select vertical/horizontal separately. Field layout combines the general and local axis.
labelCol and wrapperCol use ColProps, including breakpoint maps. The field object replaces the generic entire, even if it is {}. Nested FormItems do not inherit the columns of the outer Item. labelAlign selects left/right, labelWrap enables wrapping. colon works for horizontal labels, and FormItem.colon:true takes precedence over Form.colon:false. Columns show individual settings and an action line with label:null.
label accepts text, number, array or snippet. null preserves the alignment offset; false, undefined and the empty string remove the signature without this offset. For a rich label, the component binds control via aria-labelledby; The control's own aria-label takes precedence. Do not put the second field inside the signature.
FormItem.tooltip accepts content or a Tooltip object with an icon-snippet. Form.tooltip and ConfigProvider.form.tooltip set defaults, but without the tooltip field the icon does not appear. Signatures and explanations use their own accessible icon button to open from the keyboard. The standard icon is not a separate Tab stop.
requiredMark only changes the design: true, false, optional or snippet with label and { required }. The check remains in rules. For optional, ConfigProvider.locale.Form.optional is localized; mandatory marks show options. If a label contains a snippet, the native renderer should render it via @render rather than converting it to a string.
Binding without its own wrapper
FormItem without name is a layout container: it does not create binding, native name and field rules. You can nest several named FormItems in it, as in composite field.
noStyle leaves pure binding without layout. Messages from named noStyle fields are collected by the nearest styled Item; help:false disables message passing. The visual status is inherited until its own metadata or validateStatus defines it. value/callback are still passed explicitly.
hidden saves DOM control, value and validation registration. This is different from uninstalling via Svelte if: with unmount, local rules are removed. Hidden field remains mandatory even without a visible block. The hidden/noStyle combination creates a hidden wrapper.
help is shown when there are no errors/warnings. extra stays close to them. Both areas accept rich content and participate in aria-describedby; reset recreates their contents along with the field. label, tooltip, help and extra are isolated from field binding: decorative control should not receive the name/id of the main field.
Visual status and metadata
Automatic status considers validating first, then errors, warnings and touched. With hasFeedback enabled, successful completed validation also produces success even when the field is not touched. validateStatus overrides the visual status; an empty string disables automatic status. It does not clear model messages: a real error still sets aria-invalid even with success or an empty visual status.
useFormItemStatus is called when a child component under the desired FormItem is initialized. The returned object contains readonly getter fields status/errors/warnings. Read item.status in markup or $derived: destructuring saves snapshot. Outside Item status is undefined; pristine Item has an empty string. Field status shows separate child readout and override change without losing errors.
hasFeedback adds an icon for the current status. Input controls, selection controls and date and time controls show the supported components. In these examples, validateStatus only controls appearance; the field status example demonstrates validation rules.
Form.feedbackIcons receives ({ status, errors, warnings }) and returns a map of icons by status. FormItem.hasFeedback={{ icons }} replaces the renderer for one field. A false map value hides the icon while retaining messages and validation. Values of null, undefined, '' and 0 use the default icon. Custom icons demonstrate form defaults, a local override and success after validating untouched fields.
A noStyle field inherits feedback from its parent field unless hasFeedback is explicitly set. A nested Form starts a new feedback context. InputOTP does not display these icons; Transfer receives the status and feedback class without a separate icon.
Nested names and updating values
NamePath is a string, number, or array of segments. The string profile.name denotes one literal key; the path ['profile', 'name'] accesses a field within the object. The numeric segment creates an array if there is no container yet; string '0' creates an object key. Example of nested paths shows separate values for dot string and segment array.
getFieldValue(path) reads the path, setFieldValue(path, value) replaces its entire value. setFieldsValue recursively merges ordinary objects while preserving adjacent properties; arrays are replaced entirely. The “Update name only” button in the example saves the profile email.
For nested errors, use getFieldError(path) or getFieldsError(paths?). The FormValidationError.errorFields error also contains name segment arrays and errors messages. The errors model property shows only top-level errors. The native name of the control is collected via _; if necessary, pass the control your own name. To send the structure, use the values from onFinish.
Dynamic and nested lists
FormList manages the array of the nearest Form and passes strings, operations and errors to snippet children(fields, operation, meta). Dynamic list shows adding to the end and beginning, deleting and moving. Each line contains the current index field.name and the stable index field.key; Key Svelte each to field.key so that the permutation preserves the control instance and line errors.
The names of FormItem and nested FormList are counted from the nearest list: name={[field.name, 'name']}. Model methods always receive the full path: ['users', field.name, 'name']. Nested Lists continue this rule for teams and participants. A separate nested Form starts a new paths context.
add(value, insertIndex?) without index appends to the end; remove(index) also accepts an array of indexes; move(from, to) carries the value along with the key. Drag and drop is not built in: the example uses the "Above" button.
An array of the initialValues form takes precedence, including the empty []. If there is no array, the list uses its initialValue. resetFields() returns the original data and recreates the row controls; The nested list example restores the initialValue list. Hiding a list preserves the values but removes its local rules.
FormList rules only support custom validator(value, values). Pass meta.errors and meta.warnings to FormErrorList; example requires two participants and sets the message area to the alert or status role. FormList does not automatically add a DOM wrapper, signature, or error output. The rule with warningOnly: true creates an alert that does not block sending.
Check and send
Automatic validation runs on onChange by default. Set validateTrigger on Form for shared defaults or on Form.Item for one field. For example, onBlur validates when focus leaves the control. Use false to disable event-driven validation. Submission and validateFields() still validate fields.
Top level rules can be passed to createForm; they work without FormItem in the DOM. FormItem.rules sets local rules, including for a nested path, and takes precedence over model rules. Explicit rules={[]} disables the model rules for this field. When a FormItem is deleted, its local rules are removed and the value is retained.
required, min, max and pattern cover simple restrictions. Its validator(value, values) returns the error text or undefined; asynchronous verification returns a Promise of the same result. Asynchronous example shows wait and protection against stale response. Conditional check changes FormItem.rules, then explicitly runs validation through touchField.
Mandatory marker and verification are two different things. FormItem.required controls the signature and rule required checks the value. For mandatory consent, check true in your own validator: false by itself is not considered a null value.
| Result | Where to process |
|---|---|
| All rules are met | onFinish(values) |
| Field validation error | onFinishFailed(error) |
Error inside onFinish |
onError(error) |
To send, use Button with htmlType="submit". While the Promise from onFinish is not completed, the model retains isSubmitting; the form blocks resubmission and disables its controls. Submission example separates query errors and field errors by storing the entered data for retry.
validateFields() runs the check without sending and returns the checked values or rejects the Promise with errors. In validateFields([['profile', 'name']]) you can select paths to check; a successful result still contains a snapshot of the entire model, whereas Ant Design returns the selected part. The method accepts options as the first argument or after the list of paths. The validateFields and submit methods can be learned in model example.
Rule types and formats
type checks the value without converting store. The line '12' does not pass number or integer; the conversion is done explicitly in the owner handler. float requires a fractional number and rejects an integer. boolean with required takes false. Value types allow you to compare a string and a number in a model.
| Type | What is being checked |
|---|---|
string |
Line; length is calculated in Unicode code points |
number / integer / float |
Number without NaN / integer / non-integer |
boolean |
Boolean value |
array / object |
Array / non-null object other than array; object doesn't mean just plain object |
date |
Valid date; the matching string or timestamp is converted only for the duration of the check |
regexp / method / any |
RegExp or valid input for its constructor/function/any type |
email / url / hex / tel |
Format email, URL, HEX color or phone |
enum |
Strict match with one of the values enum |
pattern |
Checking a string value using the pattern pattern |
enum is only enabled together with type: 'enum'. pattern accepts a RegExp or expression string. Formats and enumerations shows these restrictions without querying the server: a successful email or URL check does not confirm the address's availability.
Numerical validation does not guarantee finiteness: use Number.isFinite in the validator if necessary. The date's min/max/len are compared with the timestamp. To limit the length, specify the appropriate type: not all types use min/max/pattern. When type is explicit, the own validator replaces the built-in constraints of this rule; For independent checks, set separate rules.
Factories and nested rules
FormRule - object ValidationRule or synchronous ValidationRuleFactory: (form) => ValidationRule. The factory gets the current FormInstance and can read other values via getFieldValue. It is called when checking and determining if it is required, so it should be clean, without queries or side effects. Asynchronous factories are not supported; The factory exception remains a runtime error. Current rule reads the modifiable minimum from the model.
For type: 'object' and type: 'array', the fields property specifies the rules for child keys. defaultField checks the elements of the array, and the object has its own keys without an explicit fields rule. Nested rules accept objects, not factories. The optional absent parent is skipped. For an array, defaultField is launched after successful check of the parent and explicitly specified fields; sparse gaps are not checked.
This is checking the contents of a single binding: errors on child values go to the parent FormItem and do not register their own NamePath. If you need separate labels, metadata and focus of child fields, use named FormItem and FormList. Nested rules compares object and array; FormList.rules still only accepts custom validator.
Messages and localization of check
FormItem.messageVariables substitutes strings into messages of the form ${label}: минимум ${min}. Path name, rule parameters and label are available. For a rich label, specify the string alias explicitly: without it, the field name is used. Message Variables change the signature in the error, preserving the value and constraint.
The substitution is performed once. The unknown variable becomes the string undefined; \${label} saves the literal text ${label} in the finished template. In a JavaScript string literal, the backslash must be escaped. Custom variables only change the display, even if they override the name min or label.
ValidateMessages specifies general built-in error texts. Priority: rule.message → Form.validateMessages → ConfigProvider.form.validateMessages → locale.Form.defaultValidateMessages → embedded Russian text. Message templates show the priority of local messages and the provider.
Groups types, string, number, array, date and pattern are partially specified. Provider combines groups with a locale, and a local Form replaces the entire nested group specified: string: { min: ... } does not preserve the provider's string.max. The missing template gets inline text.
ValidateMessage - string or function () => string. Strings support printf markers %s, %d, %j, %%, then variable substitutions. Changing settings is applied at the next check; errors already shown are not automatically translated. For each Form, use its own model: if several Forms share one model, the messages are set by the last registered form.
Order, delay and rule transformation
validateFirst belongs to FormItem. false runs the rules in parallel and collects all messages, true sequentially stops at the first error, parallel selects the first completed blocking error. The warning does not bypass pending blocking rules: this is a deliberate difference from the observed upstream race. Order of rules shows messages and number of calls.
validateDebounce delays automatic validation after blur and touched field changes. The new check replaces the pending one; reset and deleting the field cancel the wait. validateFields and submit are checked immediately. validateOnly does not change the already shown check and does not cancel its timer. Debounce shows the number of calls without spoofing a network request.
transform synchronously prepares the value only for its rule. It does not change the store, values of the second validator argument, or the input of the next rule. An exception becomes an error of this rule. To change the input itself, use the owner handler and setFieldValue, as in the normalize example.
len has priority over min/max: for a number it checks the number itself, for a string it checks the number of Unicode code points, for an array it checks the number of elements. whitespace rejects a non-empty string of only spaces; an empty optional value remains valid. Exact restrictions retain the original string with spaces upon successful check after trim. List rules still only support custom validator.
Test and touched modes
FormValidateOptions contains three independent flags, the default is false. Example modes allows you to combine them when checking the ['profile'] path.
validateOnly executes the rules and returns the result without changing the errors, warnings, touched and validating shown. Validation may still reject the Promise. Already shown messages are saved; The silent check itself does not make the field dirty. It can be used to evaluate the readiness of a form without showing errors prematurely. Normal blur checking continues to work regardless of this flag.
recursive includes registered fields within the selected path. Without it, the choice ['profile'] does not check the rules of child name and email. Crossing paths do not retrigger the same field; the string and numeric segments remain distinct.
dirty selects changed, touched and already checked by normal validation fields. Specified initial values are also involved, including the empty string, 0, false, and null; a missing value or undefined does not itself include the field. Therefore, in the example, the name with the initial '' is checked immediately, and the email is checked after changing, blur, or regular checking. reset clears the dirty history, but the specified defaults remain the basis for selecting the field.
isFieldTouched(path) takes into account the field itself and known descendant models. The empty path [] answers whether at least one field is affected. In the example, name blur changes the attributes of the name, profile and entire form; silent checking does not change them. Writing a value using a setter does not in itself mean touched.
Warnings are read through getFieldWarning(path) and getFieldsError(). FormItem shows them in an accessible description without aria-invalid; errors take precedence. In the example, the short name raises a non-blocking warning.
The new validation call makes the previous Promise obsolete even when validating different fields. In this case, the visible messages of each field can be completed and updated independently: outOfDate refers to the result of the call, and not to the prohibition of showing all its field errors. Please check FormValidationError.outOfDate before using the image; protect the application result from late response and from unmounting, as in asynchronous example.
States of several fields
isFieldsTouched() reports whether at least one field is affected. isFieldsTouched(true) requires all valid bindings; FormList roots do not interfere with this condition. initialValues containers without binding and rules are not considered additional controls. Model rules and explicitly affected fields are taken into account without FormItem.
The choice of names defines groups by prefixes. isFieldsTouched([['profile']], true) will become true after blur one field inside profile. To require both fields, list both full paths: [['profile', 'name'], ['profile', 'email']]. Example of group states shows these queries side by side. The request itself does not change the metadata; writing a value does not replace blur.
isFieldsValidating() checks for the presence of the validating flag in the entire model. In isFieldsValidating(names) the names match exactly, without including children: the ['profile', 'name'] check does not include the flag for ['profile']. In the example, the name and email responses arrive via different local timers, so the flags are completed one at a time. validateOnly does not enable validating and does not interrupt the display of the status of normal validation already in progress. For fields without rules, this flag is not automatically checked; it is set manually via setFields.
Empty list of names [] returns false for isFieldsTouched and isFieldsValidating; isFieldsTouched([], true) returns true. touched's [[]] selection is one group of the entire model, so with allTouched=true it doesn't require all the individual fields. Prefer isFieldsTouched(true) for checking all bindings.
After reset, the states are cleared, and late responses from the old check do not return them. FormList controls re-register their rules: an invalid line after reset still blocks submit and receives focus. In the group states example, the metrics appear after the FormItem is registered in the browser; SSR preserves the original fields and shows “—” instead of not yet connected states.
Read values
getFieldsValue reads multiple fields without running a check or changing their state. Example of reading values compares the projection of the fields with the full store:
| Challenge | Result |
|---|---|
getFieldsValue() |
Registered FormItem/FormList and fields with model rules |
getFieldsValue(true) |
The entire store, including values without UI |
getFieldsValue([['profile']]) |
Known fields and children profile; if there are no bindings, the value of the path itself |
getFieldsValue({ filter: meta => meta?.touched ?? false }) |
Fields that have passed the metadata filter and list roots |
The name list contains full NamePath values from the model root. An empty [] returns {} without calling the filter. A string containing a dot is treated as a literal key.
Without a filter, getFieldsValue(true) returns the store itself and getFieldsValue([[]]) returns a copy. The result type is Values in both cases. Other calls return FormValueProjection<Values>, which can omit nested fields and array entries.
The filter can be passed via config or as the second argument after names/true. It receives a FormFieldMeta with name, touched, validating, errors, warnings and validated. For an explicitly requested path without binding, null is returned: check this before reading metadata. When set to true, the filter selects bindings rather than arbitrary store keys. The validated flag is set by regular checking or changing the value via setFieldsValue; validateOnly doesn't change it.
FormList projects the registered row fields, then adds the missing list root as an empty array. The root is not passed to the filter, so a filter that always returns false will still leave people: []. Complete rows with data without controls are available via true without a filter. This result of the current implementation differs from the simplified description of List in the Ant Design documentation.
FormItem is registered after mount. Therefore, during SSR and first reading, the projection is not yet required to contain UI fields; for the full initial state read true. The touched flag itself does not register a value for the projection. In the example, you can show and hide the note: store will save it, and the projection will reflect the presence of the control.
Field values and states
Pass fields to control fields externally. Form applies the values and metadata after mount. During editing and validation, onFieldsChange receives the changed fields and the full snapshot. Applying fields does not call the callback.
setFields(entries) applies the FormFieldData entries in order. One entry can specify value, errors, warnings, touched and validating. When updating metadata, missing properties are preserved: updating errors does not reset warnings or touched. An empty message array or explicit undefined clears errors/warnings; value with undefined writes an empty value, and the absence of value does not change it.
Batch update applies a locally prepared server response: changes the login, shows an error and warning, and notes touched. The validator counter remains the same - the method does not run the rules. Metadata is only valid for known bindings or fields with model rules. The value can be written without the UI; metadata of such a path is ignored and is not deferred to a future mount.
Normal field validation with rules can replace manually specified messages. For a field without rules, manual errors/warnings/validating are saved; by themselves they do not block validateFields or submit. For blocking validation, add a validator. Do not use manual validating as proof of a working Promise: it is set and removed by the application.
Explicit validating=false also sets calculated validated=true without running the rules. The validated input does not override this computed flag. undefined for touched/validating is normalized to false. Changing value cancels the previous validation of the affected fields and removes their validating unless a new explicit flag is set. The old validator does not rewrite messages for the fresh value; simply updating messages without changing value does not cancel the active check.
Initial field values
The form's initialValues takes precedence over FormItem.initialValue, including null, false, 0, and the empty string. The initialValue of the field is filled with undefined before the control is rendered, without marking the touched field. Changing prop does not overwrite the current value, but is applied during the next reset. Example separates the current draft from the new default.
For one path, do not set competing initialValue of several Items. When the last registration is deleted, reset is no longer required to restore the default of the disappeared field. Inside FormList, set defaults on the form, list, or via add(defaultValue), and not on individual Item lines.
Selective reset
resetFields(names?) restores values taking into account the priorities of the form's initialValues and registered initialValue fields. Without an argument, the entire model is reset; with a list - only selected paths. Selective reset example compares values, metadata and re-creation of controls.
| Challenge | Values | Field status |
|---|---|---|
resetFields() |
Whole model | All model fields |
resetFields([['profile', 'name']]) |
One nested name | Only binding with this exact path |
resetFields([['profile']]) |
profile object with children | Only binding of the profile itself, if it exists |
resetFields(['people']) |
List array | The selected FormList recreates the rows |
resetFields([]) |
No changes | No changes |
resetFields([[]]) |
Whole store | Metadata of named fields is not selected |
The selection of metadata is precise, without automatically including descendants. In the example, the profile itself does not have a FormItem, so resetting the object will update the visible value of the name, but will preserve its touched/errors. To clear the name state, pass the full path ['profile', 'name']. The line with the dot remains the literal key; the numeric and string segments are different. Repeating a path does not duplicate a reset, and an unknown path gets undefined without creating a binding.
The contents of the selected FormItem are recreated, including a local draft and cleanup of controls. Its entire snippet, including nested FormItems, goes through the usual unmount/mount. This applies to regular fields when completely reset, as well as rows of the selected FormList. State stored by the parent component outside of these blocks must be reset separately. Unselected adjacent fields retain their controls, drafts, and selection; changing the data structure can separately change the composition of rows through the normal lifecycle of the list.
The associated native control restores focus after re-creation if the owner remains on the page and the user does not change focus. This keeps the draft InputNumber running on a soft reset. Pressing a button that puts focus on it should not force it back into the field.
FormList initialValues of forms take precedence over the current initialValue of the root list. If there is no form value, the default of the list is applied; if multiple lists set initialValue to the same path, reset does not select an arbitrary default. After re-creation, row rules and persistent list keys continue to work.
Reset protects against late validation: the former result does not return a reset field error. In the example, you can run a name check, reset the exact path, and wait for an outdated result message. An unselected check may also become outOfDate after changing the shared snapshot, so always check for this attribute.
Scrolling, ref and focus errors
getFieldInstance(name) returns the published ref of the mounted control; before mount and after removal - undefined. focusField delegates to focus ref, otherwise uses the associated native control. FormItem.controlRef allows you to explicitly pass a ref to your own composition and takes precedence over built-in registration.
scrollToField(name, options) scrolls to a ref or native id and respects CSS scroll-margin. The default if-needed behavior aligns to the nearest edge. Set focus: true to also call focusField. boundary limits which scroll containers are visited. behavior accepts a native behavior or a callback receiving the calculated actions. The returned Promise is not awaited.
Form.scrollToFirstError is executed after onFinishFailed only for the actual error. true scrolls without focus; the object supports focus, false disables the action. If the setting is missing for provider, the previous native autofocus of the first invalid control is retained. Scrolling shows local area and separate focus control.
Dependencies, Reset and Modal
Call Form.useWatch() during component initialization. Read the reactive value from markup or $derived. The hook accepts a field path or a selector. Set preserve: true to include unregistered fields. The watch example updates a greeting with the name, and the registration example shows dependent validation.
resetFields() returns initial values, clears metadata and recreates the contents of the registered FormItem and FormList. For the shape part use selective reset. For data loaded after the model was created, use setFieldsValue: changing the defaultValue of individual controls will not update the model. Reset the state of the parent component separately.
In example of a form in Modal, the application explicitly chooses when to reset and close the window. Hiding a window does not in itself mean clearing the values. A save error should leave an opportunity to correct the data or repeat the request.
Don't nest native HTML forms within each other. If an internal group needs a common Form context without additional DOM, use component={false}. This Form does not add its own submit/reset handlers; sending is owned by the external form. Context without wrapper shows the general model and a separate variant.
General settings and semantic design
Form.size and Form.disabled set defaults to child controls, including nested compositions. The local prop control and the closest ConfigProvider take precedence; isSubmitting additionally blocks repeated actions. Form.variant maintains the separate inheritance order shown in the context without a wrapper.
ConfigProvider.form sets colon, labelAlign, labelWrap, requiredMark, tooltip, scrollToFirstError and decoration. A nested record, including {}, replaces the entire parent record. Local props Form take precedence. size/disabled are not included in this record.
classNames/styles support root/label/content/help/helpItem/extra object or callback from resolved props. Classes are accumulated, CSS lines follow local styling priority; local style overrides styles.root. FormItem.rootClassName/style refers to the layout root. Semantic example combines defaults provider and callback Form without manually searching internal DOM nodes.
Examples
Regular shape
Required fields, labels, errors, focus and reset.
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({
initialValues: { name: '', email: '' }, rules: ({
name: [{ required: true, message: "Enter the participant's name." }],
email: [{ required: true, message: "Enter email." }, {
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: "Check the email format."
}]
})
});
let result = $state('');
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
}
</style>
<Form {form} aria-label={("Basic form")} onFinish={values => {
result = ("" + String((values.name)) + ": " + String((values.email)) + "");
}}>
<FormItem
name="name"
label={("Member name")}
><Input
value={form.values.name}
onValueChange={next => form.setFieldValue('name', next ?? '')}
/></FormItem>
<FormItem name="email" label={("Member Email")} help={("name@example.com")}>
<Input type="email" value={form
.values.email} onValueChange={next => form.setFieldValue('email', next ?? '')} />
</FormItem>
<div class="actions">
<Button htmlType="submit" type="primary">
{("Save form participant")}
</Button>
<Button htmlType="reset" onclick={() => { result = ''; }}>
{("Clear main form")}
</Button>
</div>
</Form>
<output aria-label={("Result of the main form")}>{(result || '—')}</output>
Model methods
Fill, validateFields, submit and restore initialValues.
<script lang="ts">
import { Button, Form, FormItem, FormValidationError, Input, createForm } from '@woodger/antd';
const form = createForm({
initialValues: { project: "Documentation", owner: '' }, rules: ({
owner: [{ required: true, message: "Specify the owner of the project." }]
})
});
let result = $state('');
async function validate() {
try {
const values = await form.validateFields(); result = ("Checked: " + String((values.project)) + ", " + String((values.owner)) + "");
}
catch (error) {
if (error instanceof FormValidationError) {
result = ("Correct field errors.");
}
else {
throw error;
}
}
}
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
}
</style>
<Form {form} aria-label={("Shape Model Methods")} onFinish={values => {
result = ("Sent: " + String((values.owner)) + "");
}}>
<FormItem
name="project"
label={("Mold design")}
><Input
value={form.values.project}
onValueChange={next => form.setFieldValue('project', next ?? '')}
/></FormItem>
<FormItem
name="owner"
label={("Project owner")}
><Input
value={form.values.owner}
onValueChange={next => form.setFieldValue('owner', next ?? '')}
/></FormItem>
<div class="actions"><Button onclick={() => form.setFieldsValue({
project: 'antd-svelte',
owner: "Anna"
})}>{("Fill model")}</Button>
<Button onclick={() => { void validate(); }}>{("Check without sending")}</Button>
<Button htmlType="submit" type="primary">{("Send model")}</Button>
<Button
htmlType="reset"
onclick={() => { result = ''; }}
>{("Reset model")}</Button></div>
</Form>
<output aria-label={("Result of Form methods")}>{(result || '—')}</output>
Prepare errors, then compare the reset of the profile object and the exact name path. You can leave an incomplete numeric entry in the budget field. A full reset recreates all fields, a selective reset recreates the contents of the selected FormItem or rows of the selected FormList.
- Name touched
- Neighbor touched
- Name validating
Selective field reset
Exact paths resetFields, parent and child metadata values, re-creation of InputNumber and FormList rows, late validation.
<script lang="ts">
import { onDestroy } from 'svelte';
import {
Button,
Form,
FormItem,
FormList,
FormValidationError,
Input,
InputNumber,
createForm,
type NamePath
} from '@woodger/antd';
type Values = {
profile: { name: string; budget: number | null };
note: string;
people: { name: string }[];
};
const form = createForm<Values>({
initialValues: {
profile: { name: "Anna", budget: 12 }, note: "Neighboring field", people: [{ name: "Boris" }]
}
});
const pending = new Map<ReturnType<typeof setTimeout>, () => void>();
let result = $state('—');
let request = 0;
function checkName(value: unknown) {
return new Promise<string | void>(resolve => {
const timer = setTimeout(() => {
pending.delete(timer);
resolve(value === 'admin' ? "This name is already taken." : undefined);
}, 1200);
pending.set(timer, () => resolve());
});
}
function reset(names?: readonly NamePath[]) {
result = '—';
form.resetFields(names);
}
function prepare() {
result = ("The name and adjacent field have been changed.");
form.setFields([
{ name: ['profile', 'name'], value: 'admin', errors: ["Name error."], touched: true },
{ name: 'note', value: "Neighboring changed", errors: ["Neighbor's error."], touched: true }
]);
}
async function validateName() {
const current = ++request;
result = ("Name check...");
try {
await form.validateFields([['profile', 'name']]);
if (current === request) result = ("Name verified.");
}
catch (error) {
if (!(error instanceof FormValidationError)) {
throw error;
}
if (current === request) {
result = error.outOfDate
? ("The scan result is out of date.")
: error.errorFields.flatMap(field => field.errors).join(' ');
}
}
}
onDestroy(() => {
request++;
for (const [timer, release] of pending) {
clearTimeout(timer);
release();
}
pending.clear();
});
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-block: 16px;
}
.people { padding-top: 8px; }
p {
margin: 16px 0;
line-height: 1.7;
}
dl {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px 16px;
margin-block: 24px;
}
dt, dd { margin: 0; }
.result {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
.values {
white-space: pre-wrap;
font-family: var(--ant-font-family-code);
}
</style>
<Form {form} aria-label={("Selective reset Form")}
onFinish={() => { result = ("Form submitted."); }}
onFinishFailed={error => {
result = error.outOfDate
? ("The scan result is out of date.")
: ("Correct form errors.");
}}>
<FormItem name={['profile', 'name']} label={("Selective reset name")}
rules={([{ required: true, message: "Please enter a name." }, { validator: checkName }])}>
<Input value={form.getFieldValue(['profile', 'name'])}
onValueChange={value => form.setFieldValue(['profile', 'name'], value ?? '')} />
</FormItem>
<FormItem name={['profile', 'budget']} label={("Selective reset budget")}>
<InputNumber value={form.getFieldValue(['profile', 'budget'])}
onValueChange={value => form.setFieldValue(['profile', 'budget'], value)} />
</FormItem>
<FormItem name="note" label={("Selective reset neighbor")}>
<Input
value={form.values.note}
onValueChange={value => form.setFieldValue('note', value ?? '')}
/>
</FormItem>
<div class="people">
<FormList name="people">
{#snippet children(fields, { add })}
{#each fields as field (field.key)}
<FormItem name={[field.name, 'name']} label={("Reset Member " + String((field.name + 1)) + "")}
rules={([{ required: true, message: "Specify the name of the reset participant." }])}>
<Input value={form.getFieldValue(['people', field.name, 'name'])}
onValueChange={value => form.setFieldValue(
['people', field.name, 'name'],
value ?? ''
)} />
</FormItem>
{/each}
<div class="actions">
<Button
onclick={() => add({ name: '' })}
>{("Add reset member")}</Button>
<Button
onclick={() => reset(['people'])}
>{("Reset list only")}</Button>
</div>
{/snippet}
</FormList>
</div>
<div class="actions">
<Button onclick={prepare}>{("Prepare changes")}</Button>
<Button
onclick={() => reset([['profile', 'name']])}
>{("Reset name only")}</Button>
<Button onclick={() => reset([['profile']])}>{("Reset profile object")}</Button>
<Button
onclick={() => reset([['profile', 'budget']])}
>{("Reset budget only")}</Button>
<Button onclick={() => form.resetFields([])}>{("Empty path list")}</Button>
<Button onclick={() => reset([[]])}>{("Reset store only")}</Button>
<Button onclick={() => reset()}>{("Reset entire form")}</Button>
<Button
onclick={() => { void validateName(); }}
>{("Check name before resetting")}</Button>
<Button type="primary" htmlType="submit">{("Send after reset")}</Button>
</div>
</Form>
<p>
{("Prepare errors, then compare the reset of the profile object and the exact name path. You can leave an incomplete numeric entry in the budget field. A full reset recreates all fields, a selective reset recreates the contents of the selected FormItem or rows of the selected FormList.")}
</p>
<dl>
<dt>
{("Name touched")}
</dt><dd>
<output aria-label={("Touched name on reset")}>
{(form.isFieldTouched(['profile', 'name']) ? "yes" : "no")}
</output>
</dd>
<dt>
{("Neighbor touched")}
</dt><dd>
<output aria-label={("Touched neighbor on reset")}>
{(form.isFieldTouched('note') ? "yes" : "no")}
</output>
</dd>
<dt>
{("Name validating")}
</dt><dd>
<output aria-label={("Validating name on reset")}>
{(form.isFieldValidating(['profile', 'name']) ? "yes" : "no")}
</output>
</dd>
</dl>
<output class="result values" aria-label={("Selective reset values")}>{JSON
.stringify(
form.getFieldsValue(true),
null,
2
)}</output>
<output class="result" aria-label={("Selective reset result")}>{result}</output>
The projection includes only registered row fields. The full store also retains the role, internal and hidden note. Even if all fields are excluded, the root of the FormList remains an empty array.
Read field values
getFieldsValue: registered fields, full store, NamePath, nullable filter and FormList projection.
<script lang="ts">
import { Button, Form, FormItem, FormList, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: {
profile: { name: "Anna", note: "Internal note" },
people: [{ name: "Boris", role: "Editor" }],
internal: "Service value"
} });
let showNote = $state(false);
let result = $state(("Select reading method."));
let filterInfo = $state('—');
function show(values: unknown) {
result = JSON.stringify(values, null, 2);
filterInfo = '—';
}
function readUnbound() {
const values = form.getFieldsValue(['internal'], meta => {
filterInfo = meta === null
? 'null'
: ("Registered field");
return meta === null;
});
result = JSON.stringify(values, null, 2);
}
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 16px;
}
p {
margin: 16px 0;
line-height: 1.7;
}
output {
display: block;
margin-top: 16px;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-family: var(--ant-font-family-code);
}
</style>
<Form {form} aria-label={("Reading Form values")}>
<FormItem name={['profile', 'name']} label={("Name in projection")}>
<Input value={form.getFieldValue(['profile', 'name'])}
onValueChange={value => form.setFieldValue(['profile', 'name'], value ?? '')} />
</FormItem>
{#if showNote}
<FormItem name={['profile', 'note']} label={("Note in projection")}>
<Input value={form.getFieldValue(['profile', 'note'])}
onValueChange={value => form.setFieldValue(['profile', 'note'], value ?? '')} />
</FormItem>
{/if}
<FormList name="people">
{#snippet children(fields)}
{#each fields as field (field.key)}
<FormItem name={[field.name, 'name']} label={("Projection participant name " + String((field.name + 1)) + "")}>
<Input
value={form.getFieldValue(['people', field.name, 'name'])}
onValueChange={value => form.setFieldValue(['people', field.name, 'name'], value ?? '')}
/>
</FormItem>
{/each}
{/snippet}
</FormList>
<Button onclick={() => { showNote = !showNote; }}>
{(showNote ? "Hide note" : "Show note")}
</Button>
</Form>
<div class="actions">
<Button
onclick={() => show(form.getFieldsValue())}
>{("Read registered")}</Button>
<Button
onclick={() => show(form.getFieldsValue(true))}
>{("Read the entire store")}</Button>
<Button onclick={() => show(form.getFieldsValue([['profile']]))}>
{("Read profile")}
</Button>
<Button
onclick={() => show(form.getFieldsValue({ filter: meta => meta?.touched ?? false }))}
>{("\n Read only touched\n ")}</Button>
<Button onclick={() => show(form.getFieldsValue({ filter: () => false }))}>
{("Exclude all fields")}
</Button>
<Button onclick={readUnbound}>{("Read hidden path")}</Button>
</div>
<p>
{("The projection includes only registered row fields. The full store also retains the role, internal and hidden note. Even if all fields are excluded, the root of the FormList remains an empty array.")}
</p>
<output aria-label={("Result of getFieldsValue")}>{result}</output>
<output aria-label={("Metadata hidden path")}>{filterInfo}</output>
setFields does not run rules. Re-verification replaces login messages. For a field without rules, manual messages and validating are saved and do not themselves block sending.
- Calls validator
- Login touched
- Yes validating
Batch update fields
setFields: values, errors/warnings, touched and manual validating without automatic checking.
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { login: 'anna', note: "Field without rules" } });
let checks = $state(0);
let result = $state('—');
function applyResponse() {
form.setFields([
{
name: 'login', value: 'anna.updated', errors: ["This name is already taken."],
warnings: ["Check the spelling of the name."], touched: true
},
{ name: 'note', errors: ["Message without a rule."], validating: true }
]);
result = ("The answer was applied without running the rules.");
}
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
p {
margin: 16px 0;
line-height: 1.7;
}
dl {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px 16px;
margin-top: 24px;
}
dt, dd { margin: 0; }
.result {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("Batch update Form")}
onFinish={values => { result = ("Sent: " + String((values.login)) + "."); }}
onFinishFailed={() => { result = ("Rules failed."); }}>
<FormItem name="login" label={("Login for setFields")} rules={([{
validator: value => {
checks++;
return typeof value === 'string' && value.length >= 3
? undefined : "Enter at least three characters.";
}
}])}>
<Input value={form.values.login}
onValueChange={value => form.setFieldValue('login', value ?? '')} />
</FormItem>
<FormItem name="note" label={("Note without rules")}>
<Input value={form.values.note}
onValueChange={value => form.setFieldValue('note', value ?? '')} />
</FormItem>
<div class="actions">
<Button onclick={applyResponse}>{("Apply server response")}</Button>
<Button onclick={() => form.setFields([{ name: 'login', errors: [] }])}>
{("Clear login error")}
</Button>
<Button onclick={() => form.setFields([{ name: 'note', validating: false }])}>
{("\n End manual check\n ")}
</Button>
<Button type="primary" htmlType="submit">{("Check and send")}</Button>
<Button htmlType="reset" onclick={() => { checks = 0; result = '—'; }}>
{("Reset setFields")}
</Button>
</div>
</Form>
<p>
{("setFields does not run rules. Re-verification replaces login messages. For a field without rules, manual messages and validating are saved and do not themselves block sending.")}
</p>
<dl>
<dt>
{("Calls validator")}
</dt><dd>
<output aria-label={("Calls to setFields rules")}>
{checks}
</output>
</dd>
<dt>
{("Login touched")}
</dt><dd>
<output aria-label={("Touched login setFields")}>
{(form.isFieldTouched('login') ? "yes" : "no")}
</output>
</dd>
<dt>
{("Yes validating")}
</dt><dd>
<output aria-label={("Manual validating setFields")}>
{(form.isFieldsValidating() ? "yes" : "no")}
</output>
</dd>
</dl>
<output class="result" aria-label={("Result of setFields")}>{result}</output>
Nested paths and field rules
NamePath, literal key with dot, local rules and partial object update.
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from '@woodger/antd';
type Values = {
profile: { name?: string; email: string };
'profile.name': string;
};
const form = createForm<Values>({ initialValues: {
profile: { email: 'anna@example.com' },
'profile.name': "Literal key"
} });
let result = $state('');
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("Nested form paths")}
onFinish={values => { result = JSON.stringify(values, null, 2); }}
onFinishFailed={error => { result = JSON.stringify(error.errorFields, null, 2); }}>
<FormItem name={['profile', 'name']} label={("Profile name")}
rules={([{ required: true, message: "Enter a profile name." }])}>
<Input value={form.getFieldValue(['profile', 'name']) ?? ''}
onValueChange={value => form.setFieldValue(['profile', 'name'], value ?? '')} />
</FormItem>
<FormItem name={['profile', 'email']} label={("Profile Email")}
rules={([{ required: true, message: "Enter profile email." }])}>
<Input type="email" value={form.getFieldValue(['profile', 'email'])}
onValueChange={value => form.setFieldValue(['profile', 'email'], value ?? '')} />
</FormItem>
<FormItem name="profile.name" label={("Literal key profile.name")}>
<Input value={form.getFieldValue('profile.name')}
onValueChange={value => form.setFieldValue('profile.name', value ?? '')} />
</FormItem>
<div class="actions">
<Button onclick={() => form.setFieldsValue({ profile: { name: "Anna" } })}>
{("Update name only")}
</Button>
<Button htmlType="submit" type="primary">{("Submit profile")}</Button>
<Button
htmlType="reset"
onclick={() => { result = ''; }}
>{("Reset profile")}</Button>
</div>
</Form>
<output aria-label={("Result of nested paths")}>{(result || '—')}</output>
Test modes
validateOnly, recursive and dirty for profile path. The name has an initial value, the email is missing; isFieldTouched takes children into account.
<script lang="ts">
import { onDestroy } from 'svelte';
import {
Button,
Checkbox,
Form,
FormItem,
FormValidationError,
Input,
createForm,
type FormValidateOptions
} from '@woodger/antd';
const form = createForm<{ profile: { name: string; email?: string } }>({
initialValues: { profile: { name: '' } }
});
let validateOnly = $state(true);
let recursive = $state(true);
let dirty = $state(false);
let checking = $state(false);
let result = $state('');
let revision = 0;
function clearResult() {
revision++;
checking = false;
result = '';
}
async function validate() {
const current = ++revision;
const options: FormValidateOptions = { validateOnly, recursive, dirty };
checking = true;
try {
const values = await form.validateFields([['profile']], options);
if (current === revision) {
result = ("Verification passed: " + String((JSON.stringify(values))) + "");
}
}
catch (error) {
if (!(error instanceof FormValidationError)) {
throw error;
}
if (current === revision) {
result = error.outOfDate
? ("The scan result is out of date.")
: error.errorFields.flatMap(
field => field.errors
).join(' ');
}
} finally {
if (current === revision) checking = false;
}
}
onDestroy(() => { revision++; });
</script>
<style>
.options, .actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.options { margin-bottom: 24px; }
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<div class="options">
<Checkbox bind:checked={validateOnly}>validateOnly</Checkbox>
<Checkbox bind:checked={recursive}>recursive</Checkbox>
<Checkbox bind:checked={dirty}>dirty</Checkbox>
</div>
<Form {form} aria-label={("Form checking modes")}>
<FormItem name={['profile', 'name']} label={("Profile name to check")}
help={("The initial value is set.")} rules={([
{ required: true, message: "Enter a name to check." },
{ min: 3, warningOnly: true, message: "It is better to use the full name." }
])}>
<Input value={form.getFieldValue(['profile', 'name'])}
onValueChange={value => {
clearResult();
form.setFieldValue(['profile', 'name'], value ?? '');
}} />
</FormItem>
<FormItem name={['profile', 'email']} label={("Email profile for verification")}
help={("Without initial value.")}
rules={([{ required: true, message: "Enter email to verify." }])}>
<Input value={form.getFieldValue(['profile', 'email']) ?? ''}
onValueChange={value => {
clearResult(); form.setFieldValue(
['profile', 'email'],
value ?? ''
);
}} />
</FormItem>
<div class="actions">
<Button loading={checking} onclick={() => { void validate(); }}>
{("Check profile")}
</Button>
<Button htmlType="reset" onclick={clearResult}>{("Reset check")}</Button>
</div>
</Form>
<output aria-label={("Result of test modes")}>{(result || '—')}</output>
<output aria-label={("Validation fields affected")}>{("\n Name: ")}{(form.isFieldTouched(['profile', 'name']) ? "yes" : "no")}{(" Profile: ")}{(form.isFieldTouched(
[
'profile'
]
) ? "yes" : "no")}{(" All form: ")}{(form.isFieldTouched([]) ? "yes" : "no")}
</output>
Touched
- At least one field
- All form fields
- Group profile
- Both profile fields
Validating
- Any field is checked
- Name is being checked
- Email is being verified
- The profile itself is checked
Multiple field states
isFieldsTouched: any field, all fields and groups. isFieldsValidating: precise paths, normal and silent validation. The responses are simulated by local timers.
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import { Button, Form, FormItem, FormValidationError, Input, createForm } from '@woodger/antd';
const form = createForm({
initialValues: {
profile: { name: 'anna', email: 'anna@example.com' }
}
});
const pending = new Map<ReturnType<typeof setTimeout>, () => void>();
let mounted = $state(false);
let result = $state('');
let revision = 0;
function checkAvailability(value: unknown, reserved: string, delay: number, message: string) {
return new Promise<string | void>(resolve => {
const timer = setTimeout(() => {
pending.delete(timer);
resolve(value === reserved ? message : undefined);
}, delay);
pending.set(timer, () => resolve());
});
}
let touched = $derived([
{ label: "At least one field", value: form.isFieldsTouched() },
{ label: "All form fields", value: form.isFieldsTouched(true) },
{ label: "Group profile", value: form.isFieldsTouched([['profile']], true) },
{
label: "Both profile fields", value: form.isFieldsTouched([
['profile', 'name'], ['profile', 'email']
], true)
}
]);
let validating = $derived([
{ label: "Any field is checked", value: form.isFieldsValidating() },
{ label: "Name is being checked", value: form.isFieldsValidating([['profile', 'name']]) },
{ label: "Email is being verified", value: form.isFieldsValidating([['profile', 'email']]) },
{ label: "The profile itself is checked", value: form.isFieldsValidating([['profile']]) }
]);
function clearResult() {
revision++;
result = '';
}
async function validate(validateOnly: boolean) {
const current = ++revision;
result = validateOnly
? ("Silent check…")
: ("Checking…");
try {
await form.validateFields([['profile']], { recursive: true, validateOnly });
if (current === revision) result = ("Verification passed.");
}
catch (error) {
if (!(error instanceof FormValidationError)) {
throw error;
}
if (current === revision) {
result = error.outOfDate
? ("The scan result is out of date.")
: error.errorFields.flatMap(
field => field.errors
).join(' ');
}
}
}
onMount(() => { mounted = true; });
onDestroy(() => {
revision++;
for (const [timer, release] of pending) {
clearTimeout(timer);
release();
}
pending.clear();
});
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.states {
display: grid;
gap: 16px;
margin-top: 24px;
}
.title {
margin: 0 0 12px;
font-weight: 600;
}
dl {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px 16px;
margin: 0;
}
dt, dd { margin: 0; }
.result {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("States of several form fields")}>
<FormItem
name={['profile', 'name']}
label={("Name for Form states")}
help={("The admin name is taken.")}
rules={([
{ required: true, message: "Enter a profile name." },
{ validator: value => checkAvailability(value, 'admin', 1200, "This name is already taken.") }
])}
>
<Input value={form.getFieldValue(['profile', 'name'])}
onValueChange={value => {
clearResult();
form.setFieldValue(['profile', 'name'], value ?? '');
}} />
</FormItem>
<FormItem
name={['profile', 'email']}
label={("Email for Form states")}
help={("The address taken@example.com is busy.")}
rules={([
{ required: true, message: "Enter profile email." },
{
validator: value => checkAvailability(
value,
'taken@example.com',
1800,
"This address is already taken."
)
}
])}
>
<Input value={form.getFieldValue(['profile', 'email'])}
onValueChange={value => {
clearResult(); form.setFieldValue(
['profile', 'email'],
value ?? ''
);
}} />
</FormItem>
<div class="actions">
<Button onclick={() => { void validate(false); }}>{("Check fields")}</Button>
<Button onclick={() => { void validate(true); }}>{("Check quietly")}</Button>
<Button htmlType="reset" onclick={clearResult}>{("Reset states")}</Button>
</div>
</Form>
<div class="states">
<div>
<p class="title">Touched</p>
<dl>{#each touched as state (state.label)}<dt>{(state.label)}</dt><dd><output
aria-label={(state.label)}
>{(mounted ? (state.value ? "yes" : "no") : '—')}</output></dd>{/each}</dl>
</div>
<div>
<p class="title">Validating</p>
<dl>{#each validating as state (state.label)}<dt>{(state.label)}</dt><dd><output
aria-label={(state.label)}
>{(mounted ? (state.value ? "yes" : "no") : '—')}</output></dd>{/each}</dl>
</div>
</div>
<output
class="result"
aria-label={("Group check result")}
>{(result || '—')}</output>
Dynamic list
FormList: adding, inserting, deleting, moving, persistent keys and custom validation.
<script lang="ts">
import { Button, Form, FormErrorList, FormItem, FormList, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { users: [{ name: "Anna" }, { name: "Boris" }] } });
let result = $state('');
</script>
<style>
fieldset {
min-width: 0;
margin: 0 0 16px;
padding: 16px;
border: 1px solid var(--ant-color-border);
border-radius: 6px;
}
legend { padding-inline: 6px; }
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.submit { margin-top: 24px; }
.messages { margin-block: 16px; }
output {
display: block;
margin-top: 16px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("List of form participants")}
onFinish={values => { result = JSON.stringify(values, null, 2); }}
onFinishFailed={() => { result = ''; }}>
<FormList name="users" rules={([{
validator: value => Array.isArray(value) && value.length >= 2
? undefined : "Add at least two participants."
}])}>
{#snippet children(fields, { add, remove, move }, meta)}
{#each fields as field (field.key)}
<fieldset>
<legend>{("Member ")}{(field.name + 1)}</legend>
<FormItem name={[field.name, 'name']} label={("Member name " + String((field.name + 1)) + "")}
rules={([{ required: true, message: "Enter the name of the list member." }])}>
<Input
value={form.getFieldValue(['users', field.name, 'name'])}
onValueChange={value => form.setFieldValue(
['users', field.name, 'name'],
value ?? ''
)}
/>
</FormItem>
<div class="actions">
<Button
aria-label={("Raise member " + String((field.name + 1)) + "")}
disabled={field.name === 0}
onclick={() => move(field.name, field.name - 1)}
>{("Above")}</Button>
<Button danger aria-label={("Remove member " + String((field.name + 1)) + "")}
onclick={() => remove(field.name)}>{("Delete")}</Button>
</div>
</fieldset>
{/each}
<div class="actions">
<Button
type="dashed"
onclick={() => add({ name: '' })}
>{("Add member")}</Button>
<Button
onclick={() => add({ name: '' }, 0)}
>{("Insert participant first")}</Button>
</div>
<div class="ant-form-item messages" role={meta.errors.length ? 'alert' : meta.warnings.length
? 'status'
: undefined}>
<FormErrorList errors={meta.errors} warnings={meta.warnings} />
</div>
{/snippet}
</FormList>
<div class="actions submit">
<Button htmlType="submit" type="primary">{("Send list")}</Button>
<Button
htmlType="reset"
onclick={() => { result = ''; }}
>{("Reset list")}</Button>
</div>
</Form>
<output aria-label={("Participant list result")}>{(result || '—')}</output>
Nested lists
Relative names of FormItem, full model paths, list initialValue and reset.
<script lang="ts">
import { Button, Form, FormItem, FormList, Input, createForm } from '@woodger/antd';
interface Team { title: string; members: { name: string }[]; }
const form = createForm<{ teams?: Team[] }>({ initialValues: {} });
let result = $state('');
</script>
<style>
fieldset {
min-width: 0;
margin: 0 0 16px;
padding: 16px;
border: 1px solid var(--ant-color-border);
border-radius: 6px;
}
legend { padding-inline: 6px; }
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-block: 16px;
}
output {
display: block;
margin-top: 16px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("Nested lists of form")}
onFinish={values => { result = JSON.stringify(values, null, 2); }}>
<FormList name="teams" initialValue={[{ title: "Edition", members: [{ name: "Anna" }] }]}>
{#snippet children(teams, { add: addTeam, remove: removeTeam })}
{#each teams as team (team.key)}
<fieldset>
<legend>{("Team ")}{(team.name + 1)}</legend>
<FormItem name={[team.name, 'title']} label={("Team name " + String((team.name + 1)) + "")}
rules={([{ required: true, message: "Enter the command name." }])}>
<Input
value={form.getFieldValue(['teams', team.name, 'title']) ?? ''}
onValueChange={value => form.setFieldValue(
['teams', team.name, 'title'],
value ?? ''
)}
/>
</FormItem>
<FormList name={[team.name, 'members']}>
{#snippet children(members, { add, remove })}
{#each members as member (member.key)}
<FormItem name={[member.name, 'name']}
label={("Team member " + String((team.name + 1)) + "." + String((member.name + 1)) + "")}
rules={([{
required: true,
message: "Enter the name of the team member."
}])}>
<Input value={form.getFieldValue([
'teams',
team.name,
'members',
member.name,
'name'
]) ?? ''}
onValueChange={value => form.setFieldValue([
'teams',
team.name,
'members',
member.name,
'name'
], value ?? '')} />
</FormItem>
<div class="actions">
<Button
danger
aria-label={("Remove team member " + String((team.name + 1)) + "." + String((member.name + 1)) + "")}
onclick={() => remove(member.name)}
>{("Remove member")}</Button>
</div>
{/each}
<Button type="dashed" aria-label={("Add a member to the team " + String((team.name + 1)) + "")}
onclick={() => add({ name: '' })}>{("Add member")}</Button>
{/snippet}
</FormList>
<div class="actions">
<Button danger aria-label={("Delete command " + String((team.name + 1)) + "")}
onclick={() => removeTeam(team.name)}>{("Delete command")}</Button>
</div>
</fieldset>
{/each}
<Button type="dashed" onclick={() => addTeam({ title: '', members: [] })}>
{("Add command")}
</Button>
{/snippet}
</FormList>
<div class="actions">
<Button htmlType="submit" type="primary">{("Send commands")}</Button>
<Button
htmlType="reset"
onclick={() => { result = ''; }}
>{("Reset commands")}</Button>
</div>
</Form>
<output aria-label={("Result of nested lists")}>{(result || '—')}</output>
Field layout
vertical/horizontal/inline and local layout of a separate FormItem.
<script lang="ts">
import { Checkbox, Form, FormItem, Input, RadioGroup, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { name: "Anna", project: 'antd-svelte' } });
let layout = $state<'vertical' | 'horizontal' | 'inline'>('vertical');
let verticalProject = $state(false);
</script>
<style>
.settings {
display: grid;
gap: 16px;
margin-bottom: 24px;
}
</style>
<div class="settings">
<RadioGroup
aria-label={("Form fields layout")}
bind:value={layout}
options={(['vertical', 'horizontal', 'inline'])}
/>
<Checkbox
bind:checked={verticalProject}
>{("Vertical project label")}</Checkbox>
</div>
<Form {form} {layout} aria-label={("Mold location")}>
<FormItem
name="name"
label={("Project participant")}
><Input
value={form.values.name}
onValueChange={next => form.setFieldValue('name', next ?? '')}
/></FormItem>
<FormItem name="project" label={("Project name")} layout={verticalProject
? 'vertical'
: undefined}>
<Input value={form.values.project} onValueChange={next => form.setFieldValue('project', next ?? '')} />
</FormItem>
</Form>
Trip, size and option
Form.disabled, Form.size and Form.variant; the general ConfigProvider remains fallback.
<script lang="ts">
import { Checkbox, ConfigProvider, Form, FormItem, Input, RadioGroup, createForm,
type ComponentSize, type Variant } from '@woodger/antd';
const form = createForm({ initialValues: { name: "Anna" } });
let disabled = $state(false);
let size = $state<ComponentSize>('medium');
let variant = $state<Variant>('outlined');
</script>
<style>
.settings {
display: grid;
gap: 16px;
margin-bottom: 24px;
}
</style>
<div
class="settings"
><Checkbox
bind:checked={disabled}
>{("Disable form")}</Checkbox>
<RadioGroup
aria-label={("Form controls size")}
bind:value={size}
options={(['small', 'medium', 'large'])}
/>
<RadioGroup
aria-label={("Input option in the form")}
bind:value={variant}
options={(['outlined', 'filled', 'borderless', 'underlined'])}
/></div>
<ConfigProvider componentSize="medium">
<Form
{form}
{disabled}
{size}
{variant}
aria-label={("Form settings")}
><FormItem
name="name"
label={("Name in form settings")}
>
<Input
value={form.values.name}
onValueChange={next => form.setFieldValue('name', next ?? '')}
/>
</FormItem></Form>
</ConfigProvider>
Context without wrapper
Form.component=false, the general model and a variant of the closest Form without a nested HTML form.
<script lang="ts">
import { Button, Checkbox, ConfigProvider, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { outer: "External field", inner: "Internal field" } });
let borderless = $state(false);
let result = $state(("The form has not been submitted yet."));
</script>
<style>
.settings { margin-bottom: 24px; }
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<div class="settings">
<Checkbox
bind:checked={borderless}
>{("Borderless in internal context")}</Checkbox>
</div>
<ConfigProvider variant="outlined" input={{ variant: 'underlined' }}>
<Form {form} variant="filled" aria-label={("Form with context without wrapper")}
onFinish={values => { result = JSON.stringify(values); }}>
<FormItem name="outer" label={("External Form field")}>
<Input value={form.values.outer} onValueChange={value => form.setFieldValue(
'outer',
value ?? ''
)} />
</FormItem>
<Form {form} component={false} variant={borderless ? 'borderless' : undefined}>
<FormItem name="inner" label={("Form field without wrapper")}>
<Input value={form.values.inner} onValueChange={value => form.setFieldValue(
'inner',
value ?? ''
)} />
</FormItem>
</Form>
<div class="actions">
<Button htmlType="submit" type="primary">{("Send general model")}</Button>
<Button htmlType="reset">{("Reset general model")}</Button>
</div>
</Form>
</ConfigProvider>
<output aria-label={("Context form result")}>{result}</output>
Observation of values
Form.useForm() creates a typed model. Form.useWatch() updates the greeting when the name changes.
<script lang="ts">
import { Form, Input } from '@woodger/antd';
const [form] = Form.useForm<{ name: string }>();
const watchedName = Form.useWatch('name', form);
let name = $derived(watchedName.value?.trim() ?? '');
let greeting = $derived(name ? `Hello, ${name}!` : "Enter a name.");
</script>
<Form {form} initialValues={{ name: "Anna" }} aria-label={("Reactive form model")}>
<Form.Item name="name" label={("Greeting name")}>
<Input value={form.values.name} onValueChange={next => form.setFieldValue('name', next ?? '')} />
</Form.Item>
</Form>
<output aria-label={("Observation Form")}>{greeting}</output>
Registration and dependencies
Password, repeat and validator with current model values.
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({
initialValues: { email: '', password: '', confirm: '' }, rules: ({
email: [{ required: true, message: "Enter your registration email." }, {
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: "Check your registration email."
}],
password: [{ required: true, message: "Enter the password." }, {
min: 8,
message: "At least eight characters."
}],
confirm: [{ required: true, message: "Repeat password." }, {
validator: (
value: unknown,
values: Readonly<{ password: string }>
) => value === values.password ? undefined : "Passwords do not match."
}]
})
});
let result = $state('');
</script>
<style>
output {
display: block;
margin-block-start: 12px;
}
</style>
<Form {form} aria-label={("Registration form")} onFinish={values => {
result = ("Registration: " + String((values.email)) + "");
}}>
<FormItem name="email" label={("Email registration")}><Input type="email" value={form
.values.email} onValueChange={next => form.setFieldValue('email', next ?? '')} /></FormItem>
<FormItem
name="password"
label={("Registration password")}
><Input
type="password"
autocomplete="new-password"
value={form.values.password}
onValueChange={next => form.setFieldValue('password', next ?? '')}
/></FormItem>
<FormItem
name="confirm"
label={("Repeat registration password")}
><Input
type="password"
autocomplete="new-password"
value={form.values.confirm}
onValueChange={next => form.setFieldValue('confirm', next ?? '')}
/></FormItem>
<Button htmlType="submit" type="primary">{("Check registration")}</Button>
</Form>
<output aria-label={("Registration result")}>{(result || '—')}</output>
Asynchronous check
Busy login, isFieldValidating and protection against outdated results.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Button, Form, FormItem, FormValidationError, Input, createForm } from '@woodger/antd';
const pending = new Map<ReturnType<typeof setTimeout>, () => void>();
const form = createForm({
initialValues: { login: '' }, rules: ({
login: [
{ required: true, message: "Enter the login to be verified." },
{
validator: value => new Promise<string | void>(resolve => {
const timer = setTimeout(() => {
pending.delete(timer); resolve(
value === 'admin' ? "This login is busy." : undefined
);
}, 300);
pending.set(timer, () => resolve());
})
}
]
})
});
let result = $state('');
let revision = 0;
async function validate() {
const current = ++revision;
try {
await form.validateFields(['login']);
if (current === revision) result = ("Login available.");
}
catch (error) {
if (!(error instanceof FormValidationError)) {
throw error;
}
if (current === revision && !error.outOfDate) {
result = ("Select another login.");
}
}
}
onDestroy(() => {
revision++; for (const [timer, release] of pending) {
clearTimeout(timer);
release();
} pending.clear();
});
</script>
<style>
output {
display: block;
margin-block-start: 12px;
}
</style>
<Form {form} aria-label={("Login check")}><FormItem name="login" label={("Verifiable login")} help={("admin is busy; the check takes 300 ms.")}>
<Input value={form.values.login} onValueChange={next => {
revision++; result = ''; form.setFieldValue(
'login',
next ?? ''
);
}} />
</FormItem><Button onclick={() => { void validate(); }}>
{("Check login availability")}
</Button></Form>
<output aria-label={("Login check Form")}>{form.isFieldValidating('login')
? ("Checking...")
: (result || '—')}</output>
Conditional check
FormItem.rules changes with the condition; touchField runs the test.
<script lang="ts">
import { tick } from 'svelte';
import { Button, Checkbox, Form, FormItem, Input, createForm } from '@woodger/antd';
let required = $state(false);
const form = createForm({ initialValues: { phone: '' } });
let result = $state('');
async function changeRequired(next: boolean) {
required = next;
await tick();
form.touchField('phone');
}
</script>
<style>
.settings { margin-bottom: 24px; }
output {
display: block;
margin-block-start: 12px;
}
</style>
<div class="settings">
<Checkbox checked={required} onCheckedChange={changeRequired}>
{("Need a phone number for contact")}
</Checkbox>
</div>
<Form {form} aria-label={("Conditional form validation")} onFinish={() => {
result = ("Check completed.");
}}>
<FormItem name="phone" label={("Contact phone")} rules={([{
required,
message: "Please provide a telephone number for contact."
}])}>
<Input value={form.values.phone} onValueChange={next => form.setFieldValue('phone', next ?? '')} />
</FormItem>
<Button htmlType="submit">{("Check conditional field")}</Button>
</Form>
<output aria-label={("Conditional Rules Form")}>{(result || '—')}</output>
Form in Modal
The external submit button is connected to the real form via form/id.
<script lang="ts">
import { Button, Form, FormItem, Input, Modal, createForm } from '@woodger/antd';
const id = $props.id();
const form = createForm({
initialValues: { project: '' }, rules: ({
project: [{
required: true,
message: "Enter the name of the new project."
}]
})
});
let open = $state(false);
let result = $state('');
</script>
<style>
output {
display: block;
margin-block-start: 12px;
}
</style>
{#snippet footer()}
<Button
onclick={() => { open = false; }}
>{("Cancel creation")}</Button>
<Button type="primary" htmlType="submit" form={`${id}-form`}>
{("Create a project from a form")}
</Button>
{/snippet}
<Button
onclick={() => { form.resetFields(); open = true; }}
>{("Open form in Modal")}</Button>
<Modal title={("New project")} bind:open {footer}>
<Form
{form}
id={`${id}-form`}
aria-label={("Creating a project in Modal")}
onFinish={values => {
result = values.project;
open = false;
}}
>
<FormItem name="project" label={("Name of the new project")}><Input value={form
.values.project} onValueChange={next => form
.setFieldValue(
'project',
next ?? ''
)} /></FormItem>
</Form>
</Modal>
<output aria-label={("Created project Form")}>{(result || '—')}</output>
Own control
The wrapper around InputNumber preserves the FormItem context and the numeric value.
CustomControl.svelte<script lang="ts"> import { Button, Form, FormItem, createForm } from '@woodger/antd'; import PriceControl from './PriceControl.svelte'; const form = createForm<{ price: number | null }>({ initialValues: { price: 1200 }, rules: ({ price: [{ required: true, message: "Enter cost." }, { min: 1, message: "The cost must be positive." }] }) }); let result = $state(''); </script> <style> output { display: block; margin-block-start: 12px; } </style> <Form {form} aria-label={("Own field component")} onFinish={values => { result = ("Saved: " + String((String(values.price))) + ""); }}><FormItem name="price" label={("Project cost")}> <PriceControl value={form.values.price} onValueChange={next => form.setFieldValue('price', next)} /> </FormItem><Button htmlType="submit" type="primary" onclick={() => { result = ''; }}> {("Check price")} </Button></Form> <output aria-label={("Cost Form")}>{(result || ("Model: " + String((String(form.values.price))) + ""))}</output>PriceControl.svelte<script lang="ts"> import { InputNumber, SpaceAddon, SpaceCompact } from '@woodger/antd'; let { value, onValueChange }: { value: number | null; onValueChange: (next: number | null) => void } = $props(); </script> <SpaceCompact> <InputNumber {value} {onValueChange} min={0} precision={2} /> <SpaceAddon>₽</SpaceAddon> </SpaceCompact>
Input normalization
Owner removes spaces and changes case to setFieldValue.
<script lang="ts">
import { Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { code: '' } });
</script>
<Form
{form}
aria-label={("Value conversion")}
><FormItem
name="code"
label={("Project code")}
help={("Spaces are removed and letters become capitalized.")}
>
<Input value={form.values.code} onValueChange={next => form.setFieldValue(
'code',
(next ?? '').replace(
/\s/g,
''
).toLocaleUpperCase()
)} />
</FormItem></Form>
<output aria-label={("Normalization Form")}>{("Model: ")}{(form.values
.code
|| '—')}</output>
Asynchronous sending
Resend blocking, pending and onFinish error.
<script lang="ts">
import { onDestroy } from 'svelte';
import { Button, Checkbox, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({
initialValues: { name: "Documentation" }, rules: ({
name: [{
required: true
}]
})
});
let fail = $state(false);
let result = $state('');
let active = true;
let timer: ReturnType<typeof setTimeout> | undefined;
let settle: (() => void) | undefined;
function submit(values: { name: string }): Promise<void> {
const failed = fail;
result = '';
return new Promise((resolve, reject) => {
settle = resolve;
timer = setTimeout(() => {
timer = undefined;
settle = undefined;
if (!active) {
resolve();
return;
}
if (failed) {
reject(new Error(("Service is temporarily unavailable.")));
}
else {
result = ("Saved: " + String((values.name)) + "");
resolve();
}
}, 400);
});
}
onDestroy(() => { active = false; clearTimeout(timer); settle?.(); });
</script>
<style>
.settings { margin-bottom: 24px; }
output {
display: block;
margin-block-start: 12px;
}
</style>
<div class="settings">
<Checkbox bind:checked={fail} disabled={form.isSubmitting}>
{("Error sending Form")}
</Checkbox>
</div>
<Form
{form}
aria-label={("Asynchronous sending")}
onFinish={submit}
onError={error => {
result = error instanceof Error ? error.message : ("Sending error.");
}}
>
<FormItem
name="name"
label={("Dispatch document")}
><Input
value={form.values.name}
onValueChange={next => form.setFieldValue('name', next ?? '')}
/></FormItem>
<Button htmlType="submit" type="primary" loading={form.isSubmitting}>
{("Submit form document")}
</Button>
</Form>
<output aria-label={("Asynchronous Form result")}>{(result || '—')}</output>
Search form
The grid and additional fields are assembled using CSS and Svelte.
<script lang="ts">
import { Button, Checkbox, Form, FormItem, Input, Select, createForm } from '@woodger/antd';
const form = createForm<{ query: string; status: 'all' | 'draft' | 'ready'; owner: string }>({
initialValues: { query: '', status: 'all', owner: '' }
});
let expanded = $state(false);
let result = $state('');
</script>
<style>
.fields {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 160px), 1fr));
gap: 16px;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("Search form")} onFinish={values => {
result = JSON.stringify(values);
}}>
<div
class="fields"
><FormItem
name="query"
label={("Search query")}
><Input
value={form.values.query}
onValueChange={next => form.setFieldValue('query', next ?? '')}
/></FormItem>
<FormItem name="status" label={("Document status")}><Select value={form.values
.status} onValueChange={next => form.setFieldValue('status', next ?? 'all')}
options={([{ value: 'all', label: "All" }, {
value: 'draft',
label: "Drafts"
}, { value: 'ready', label: "Ready" }])} /></FormItem>
{#if expanded}<FormItem name="owner" label={("Author of the document")}><Input value={form
.values.owner} onValueChange={next => form
.setFieldValue(
'owner',
next ?? ''
)} /></FormItem>{/if}
</div>
<div class="actions">
<Button htmlType="submit" type="primary">
{("Apply form filters")}
</Button>
<Button htmlType="reset" onclick={() => { result = ''; }}>
{("Reset form filters")}
</Button>
<Checkbox bind:checked={expanded}>{("Additional filters")}</Checkbox>
</div>
</Form>
<output aria-label={("Filters Form")}>{(result || '—')}</output>
Date in model
Dayjs is stored directly, without application ISO/UTC serialization.
<script lang="ts">
import dayjs, { type Dayjs } from 'dayjs';
import { Button, DatePicker, Form, FormItem, createForm } from '@woodger/antd';
const form = createForm<{ date: Dayjs | null }>({
initialValues: { date: null },
rules: ({ date: [{ required: true, message: "Select a meeting date." }] })
});
let result = $state('—');
</script>
<style>.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
} output {
display: block;
margin-top: 16px;
}</style>
<Form {form} onFinish={values => {
result = ("" + String((dayjs.isDayjs(values.date) ? 'Dayjs' : ("Not Dayjs"))) + ": " + String((values.date?.format('YYYY-MM-DD') ?? 'null')) + "");
}}>
<FormItem name="date" label={("Meeting date")}>
<DatePicker
aria-label={("Meeting date")}
value={form.values.date}
defaultPickerValue={dayjs('2026-10-15')}
onChange={date => form.setFieldValue('date', date)}
/>
</FormItem>
<div class="actions">
<Button htmlType="submit" type="primary">{("Save meeting")}</Button>
<Button
htmlType="reset"
onclick={() => { result = '—'; }}
>{("Reset meeting")}</Button>
</div>
</Form>
<output aria-label={("Date form result")}>{result}</output>
Field checked
Explicit checked/onCheckedChange and validator for consent.
<script lang="ts">
import { Button, Form, FormItem, Switch, createForm } from '@woodger/antd';
const form = createForm<{ digest: boolean }>({
initialValues: { digest: false },
rules: ({
digest: [{ validator: value => value
? undefined
: "Enable the report before saving." }]
})
});
let result = $state('');
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
color: var(--ant-color-text-secondary);
}
</style>
<Form {form} onFinish={values => {
result = ("digest: " + String((String(values.digest))) + "");
}}>
<FormItem name="digest" label={("Receive a weekly report")} required>
<Switch checked={form.values.digest} onCheckedChange={value => {
form.setFieldValue('digest', value);
result = '';
}} />
</FormItem>
<div class="actions">
<Button type="primary" htmlType="submit">{("Save")}</Button>
<Button htmlType="reset" onclick={() => { result = ''; }}>{("Reset")}</Button>
</div>
<output aria-label={("Form result")}>{result}</output>
</Form>
Semantic styles and ConfigProvider.form
Object defaults of the provider, callback styles of the form and priority of local design.
<script lang="ts">
import {
Checkbox,
ConfigProvider,
Form,
FormItem,
Input,
createForm,
type FormConfig
} from '@woodger/antd';
const form = createForm({ initialValues: { name: "Anna" } });
const defaults: FormConfig = {
colon: false,
labelAlign: 'left',
styles: {
root: `
padding: 16px;
border: 1px dashed var(--ant-color-border);
border-radius: 8px;
`,
label: 'font-weight: 600',
help: `
padding: 4px 8px;
background: var(--ant-color-fill-quaternary);
`,
extra: 'color: var(--ant-color-text-secondary)'
}
};
let highlighted = $state(true);
</script>
<style>
.settings { margin-bottom: 20px; }
</style>
<div class="settings">
<Checkbox bind:checked={highlighted}>
{("Select labels using callback styles")}
</Checkbox>
</div>
<ConfigProvider form={defaults}>
<Form {form} layout="horizontal" labelCol={{ xs: { span: 24 }, sm: { span: 8 } }}
wrapperCol={{ xs: { span: 24 }, sm: { span: 16 } }}
class="form-docs-custom-root" aria-label={("Form design")}
styles={({ props }) => ({
label: highlighted && props.layout === 'horizontal'
? `
font-weight: 700;
color: var(--ant-color-primary);
`
: undefined
})}>
<FormItem name="name" label={("Own label")} class="form-docs-custom-item"
style="margin-bottom: 0" help={("Description in slot help")} extra={("Permanent explanation in slot extra")}>
<Input
value={form.values.name}
onValueChange={next => form.setFieldValue('name', next ?? '')}
/>
</FormItem>
</Form>
</ConfigProvider>
Form Component Theme
Reactively apply label and indentation tokens, save input and RTL.
<script lang="ts">
import { Checkbox, ConfigProvider, Form, FormItem, Input, createForm } from '@woodger/antd';
let enabled = $state(true);
const form = createForm({
initialValues: { name: "Anna" },
rules: ({ name: [{ required: true }] })
});
const tokens = {
labelFontSize: 18,
labelColor: '#874d00',
itemMarginBottom: 32,
verticalLabelPadding: '0 0 16px',
labelRequiredMarkColor: '#d48806'
};
</script>
<style>
.settings { margin-bottom: 24px; }
</style>
<div class="settings">
<Checkbox bind:checked={enabled}>{("Apply Form tokens")}</Checkbox>
</div>
<ConfigProvider direction="rtl" theme={{ components: { Form: enabled ? tokens : {} } }}>
<Form {form} aria-label={("Form theme")}>
<FormItem name="name" label={("Thematic label")}>
<Input value={form.values.name}
onValueChange={next => form.setFieldValue('name', next ?? '')} />
</FormItem>
</Form>
</ConfigProvider>
Columns and transfer of labels
responsive labelCol/wrapperCol, labelAlign, labelWrap, colon and line alignment without label.
<script lang="ts">
import { Button, Checkbox, Form, FormItem, Input, RadioGroup, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { name: "Anna", project: 'antd-svelte' } });
let align = $state<'left' | 'right'>('right');
let wrap = $state(true);
let saved = $state('');
</script>
<style>
.settings {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
margin-bottom: 24px;
}
output {
display: block;
overflow-wrap: anywhere;
}
</style>
<div class="settings">
<RadioGroup aria-label={("Form Label Alignment")} options={([
'left',
'right'
])}
bind:value={align} />
<Checkbox bind:checked={wrap}>{("Move long labels")}</Checkbox>
</div>
<Form {form} layout="horizontal" labelAlign={align} labelWrap={wrap}
labelCol={{ xs: { span: 24 }, sm: { span: 8 } }}
wrapperCol={{ xs: { span: 24 }, sm: { span: 16 } }}
aria-label={("Column shape")} onFinish={() => { saved = form.values.name; }}>
<FormItem name="name" label={("Full name of the project participant")}>
<Input
value={form.values.name}
onValueChange={value => form.setFieldValue('name', value ?? '')}
/>
</FormItem>
<FormItem name="project" label={("Project")} colon={false}
labelCol={{ xs: { span: 24 }, sm: { span: 6 } }}
wrapperCol={{ xs: { span: 24 }, sm: { span: 18 } }}>
<Input value={form.values.project} onValueChange={value => form.setFieldValue(
'project',
value ?? ''
)} />
</FormItem>
<FormItem label={(null)}>
<Button htmlType="submit" type="primary">{("Save columns")}</Button>
</FormItem>
</Form>
<output aria-label={("Result of a form with columns")}>{(saved ? `Saved: ${saved}` : "Change captions or window width")}</output>
Captions, tooltip and explanations
Snippet labels and available names, general hint, rich help and permanent extra.
<script lang="ts">
import { Form, FormItem, Input, RadioGroup, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { name: "Anna", visibility: 'team' } });
</script>
<style>
.info {
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
cursor: help;
}
</style>
{#snippet nameLabel()}
<span>{("Member ")}<strong>
{("project")}
</strong></span>
{/snippet}
{#snippet visibilityLabel()}
<span>{("Visibility ")}<em>
{("profile")}
</em></span>
{/snippet}
{#snippet explanation()}
<span>{("The name is shown in the list. ")}<a href={("#form-demo-initial-values")}>
{("Initial values")}
</a></span>
{/snippet}
{#snippet extra()}<span>{("The profile can be changed later. This explanation is saved next to the error.")}</span>{/snippet}
{#snippet tooltipIcon()}
<button class="info" type="button" aria-label={("Explanation of the participant name")}>?</button>
{/snippet}
<Form {form} aria-label={("Labels and field hints")}
tooltip={({ placement: 'top', trigger: ['hover', 'focus'] })}>
<FormItem name="name" label={(nameLabel)} tooltip={({
title: "Name in workspace",
icon: tooltipIcon
})}
help={(explanation)} extra={(extra)} rules={([{
required: true,
message: "Enter the participant's name."
}])}>
<Input
aria-label={("Project participant")}
value={form.values.name}
onValueChange={value => form.setFieldValue('name', value ?? '')}
/>
</FormItem>
<FormItem name="visibility" label={(visibilityLabel)}
tooltip={({ title: "Who sees the participant card", placement: 'bottom' })}>
<RadioGroup value={form.values.visibility} options={([
{ value: 'team', label: "Team" }, { value: 'everyone', label: "All" }
])} onValueChange={value => form.setFieldValue('visibility', value)} />
</FormItem>
</Form>
Mandatory marks
Asterisk, no mark, optional and your requiredMark snippet without changing the rules.
<script lang="ts">
import {
Form,
FormItem,
Input,
RadioGroup,
createForm,
type FormRequiredMarkInfo
} from '@woodger/antd';
const form = createForm({ initialValues: { name: '', note: '' } });
let mode = $state('required');
</script>
<style>
.settings { margin-bottom: 24px; }
.mark {
margin-inline-start: 8px;
font-size: 12px;
color: var(--ant-color-text-secondary);
}
</style>
{#snippet mark(label: string, info: FormRequiredMarkInfo)}
{(label)}<span class="mark" aria-hidden="true">{(info.required ? "required" : "optional")}</span>
{/snippet}
<div
class="settings"
><RadioGroup
aria-label={("Mandatory marker Form")}
bind:value={mode}
options={([
{ value: 'required', label: "Asterisk" }, { value: 'none', label: "No marks" },
{ value: 'optional', label: "Optional" }, { value: 'custom', label: "Your text" }
])}
/></div>
<Form {form} aria-label={("Mandatory marks")}
requiredMark={mode === 'custom' ? mark : mode === 'optional' ? 'optional' : mode !== 'none'}>
<FormItem name="name" label={("Name with required rule")} rules={([{
required: true,
message: "The name is required for any marker."
}])}>
<Input
value={form.values.name}
onValueChange={value => form.setFieldValue('name', value ?? '')}
/>
</FormItem>
<FormItem name="note" label={("Optional note")}>
<Input
value={form.values.note}
onValueChange={value => form.setFieldValue('note', value ?? '')}
/>
</FormItem>
</Form>
Composite field without wrappers
Nameless layout, two noStyle bindings, error collection and local disabled/size border.
<script lang="ts">
import {
Button,
Checkbox,
ConfigProvider,
Form,
FormItem,
Input,
SpaceCompact,
createForm
} from '@woodger/antd';
const form = createForm({ initialValues: { first: '', last: '' } });
let disabled = $state(false);
let suppress = $state(false);
</script>
<style>
.settings {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-bottom: 24px;
}
</style>
<div class="settings">
<Checkbox bind:checked={disabled}>{("Disable nested controls")}</Checkbox>
<Checkbox bind:checked={suppress}>{("Do not collect last name error")}</Checkbox>
</div>
<Form {form} {disabled} size="large" aria-label={("Fields without their own wrapper")}>
<FormItem label={("Member without own name")}>
<SpaceCompact block>
<FormItem name="first" noStyle rules={([{
required: true,
message: "Enter a name."
}])}>
<Input
aria-label={("Name in noStyle")}
placeholder={("Name")}
value={form.values.first}
onValueChange={value => form.setFieldValue('first', value ?? '')}
/>
</FormItem>
<FormItem name="last" noStyle help={(suppress ? false : undefined)}
rules={([{ required: true, message: "Enter last name." }])}>
<Input
aria-label={("Last name in noStyle")}
placeholder={("Last name")}
value={form.values.last}
onValueChange={value => form.setFieldValue('last', value ?? '')}
/>
</FormItem>
</SpaceCompact>
</FormItem>
<FormItem label={("Local context")}>
<ConfigProvider componentDisabled={false} componentSize="small">
<Input
aria-label={("Independent control inside Form")}
value="Собственные disabled и size"
readonly
/>
</ConfigProvider>
</FormItem>
<FormItem label={(null)}>
<Button htmlType="submit">
{("Check compound field")}
</Button>
</FormItem>
</Form>
Field status and useFormItemStatus
Visual validateStatus separate from errors/ARIA; reactive getter fields hook.
Status.svelte<script lang="ts"> import { Button, Checkbox, Form, FormItem, Input, RadioGroup, createForm, type FormValidateStatus } from '@woodger/antd'; import StatusReadout from './StatusReadout.svelte'; const form = createForm({ initialValues: { name: '' } }); let status = $state<FormValidateStatus | 'auto'>('auto'); let feedback = $state(true); </script> <style> .settings { margin-bottom: 24px; } .actions { display: flex; flex-wrap: wrap; gap: 12px; } </style> <div class="settings" ><RadioGroup aria-label={("Visual status of FormItem")} bind:value={status} options={([ { value: 'auto', label: "Automatic" }, { value: '', label: "Without status" }, { value: 'success', label: 'success' }, { value: 'warning', label: 'warning' }, { value: 'error', label: 'error' }, { value: 'validating', label: 'validating' } ])} /></div> <div class="settings" ><Checkbox bind:checked={feedback} >{("Show validation icons")}</Checkbox></div> <Form {form} aria-label={("Status and metadata fields")}> <FormItem name="name" label={("Name to check status")} hasFeedback={feedback} validateStatus={status === 'auto' ? undefined : status} rules={([{ required: true, message: "Name is not filled in yet." }])}> <Input value={form.values.name} onValueChange={value => form.setFieldValue('name', value ?? '')} /> <StatusReadout /> </FormItem> <div class="actions"> <Button htmlType="submit">{("Show status error")}</Button> <Button htmlType="reset">{("Reset field validation")}</Button> </div> </Form>StatusReadout.svelte<script lang="ts"> import { useFormItemStatus } from '@woodger/antd'; const item = useFormItemStatus(); </script> <style> output { display: block; margin-top: 8px; overflow-wrap: anywhere; } </style> <output aria-label={("Status of the nearest FormItem")}>{(item.status === undefined ? "out of field" : item.status || "without status")}</output> <output aria-label={("Errors of the nearest FormItem")}>{(item.errors.join('; ') || ("no errors"))}</output> <output aria-label={("Warnings of the nearest FormItem")}>{(item.warnings.join('; ') || ("no warnings"))}</output>
Input validation icons
hasFeedback in Input, InputPassword, InputSearch, TextArea and InputNumber. validateStatus only changes appearance.
<script lang="ts">
import {
Checkbox,
Form,
FormItem,
Input,
InputNumber,
InputPassword,
InputSearch,
RadioGroup,
TextArea,
createForm,
type FormValidateStatus
} from '@woodger/antd';
const form = createForm({ initialValues: {} });
let status = $state<FormValidateStatus>('success');
let enabled = $state(true);
</script>
<div class="settings">
<RadioGroup
aria-label={("Input feedback status")}
bind:value={status}
options={['success', 'warning', 'error', 'validating'].map(value => ({ value, label: value }))}
/>
<Checkbox bind:checked={enabled}>{("Show validation icons")}</Checkbox>
</div>
<Form {form} aria-label={("Input validation icons")}>
<FormItem label="Input" htmlFor="feedback-input" validateStatus={status} hasFeedback={enabled}>
<Input id="feedback-input" aria-label="Input feedback" defaultValue="woodger" allowClear />
</FormItem>
<FormItem
label="InputPassword"
htmlFor="feedback-password"
validateStatus={status}
hasFeedback={enabled}
>
<InputPassword
id="feedback-password"
aria-label="InputPassword feedback"
defaultValue="password"
/>
</FormItem>
<FormItem
label="InputSearch"
htmlFor="feedback-search"
validateStatus={status}
hasFeedback={enabled}
>
<InputSearch
id="feedback-search"
aria-label="InputSearch feedback"
defaultValue="Svelte"
allowClear
/>
</FormItem>
<FormItem
label="TextArea"
htmlFor="feedback-textarea"
validateStatus={status}
hasFeedback={enabled}
>
<TextArea
id="feedback-textarea"
aria-label="TextArea feedback"
defaultValue="TypeScript"
rows={2}
allowClear
showCount
/>
</FormItem>
<FormItem
label="InputNumber"
htmlFor="feedback-number"
validateStatus={status}
hasFeedback={enabled}
>
<InputNumber
id="feedback-number"
aria-label="InputNumber feedback"
defaultValue={42}
style="width:100%"
/>
</FormItem>
</Form>
<style>
.settings {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-bottom: 24px;
}
</style>
Selection validation icons
Shared FormItem status for Select, TreeSelect, Cascader, AutoComplete and Mentions.
<script lang="ts">
import {
AutoComplete,
Cascader,
Form,
FormItem,
Mentions,
RadioGroup,
Select,
TreeSelect,
createForm,
type FormValidateStatus
} from '@woodger/antd';
const form = createForm({ initialValues: {} });
let status = $state<FormValidateStatus>('warning');
</script>
<div class="settings">
<RadioGroup
aria-label={("Selection feedback status")}
bind:value={status}
options={['success', 'warning', 'error', 'validating'].map(value => ({ value, label: value }))}
/>
</div>
<Form {form} aria-label={("Selection validation icons")}>
<FormItem label="Select" htmlFor="feedback-select" validateStatus={status} hasFeedback>
<Select
id="feedback-select"
aria-label="Select feedback"
defaultValue="svelte"
allowClear
style="width:100%"
options={[{ value: 'svelte', label: 'Svelte' }, { value: 'typescript', label: 'TypeScript' }]}
/>
</FormItem>
<FormItem label="TreeSelect" htmlFor="feedback-tree" validateStatus={status} hasFeedback>
<TreeSelect
id="feedback-tree"
aria-label="TreeSelect feedback"
defaultValue="svelte"
allowClear
style="width:100%"
treeData={[{ value: 'web', title: 'Web', children: [{ value: 'svelte', title: 'Svelte' }] }]}
/>
</FormItem>
<FormItem label="Cascader" htmlFor="feedback-cascader" validateStatus={status} hasFeedback>
<Cascader
id="feedback-cascader"
aria-label="Cascader feedback"
defaultValue={['web', 'svelte']}
allowClear
style="width:100%"
options={[{ value: 'web', label: 'Web', children: [{ value: 'svelte', label: 'Svelte' }] }]}
/>
</FormItem>
<FormItem
label="AutoComplete"
htmlFor="feedback-autocomplete"
validateStatus={status}
hasFeedback
>
<AutoComplete
id="feedback-autocomplete"
aria-label="AutoComplete feedback"
defaultValue="woodger.org"
allowClear
style="width:100%"
options={[{ value: 'woodger.org' }, { value: 'ant.design' }]}
/>
</FormItem>
<FormItem label="Mentions" htmlFor="feedback-mentions" validateStatus={status} hasFeedback>
<Mentions
id="feedback-mentions"
aria-label="Mentions feedback"
defaultValue="@woodger"
allowClear
options={[{ value: 'woodger', label: 'woodger' }, { value: 'antd', label: 'antd' }]}
/>
</FormItem>
</Form>
<style>
.settings { margin-bottom: 24px; }
</style>
Date and time icons
The default suffix shows the validation icon. A custom suffix replaces it; local suffixIcon=true overrides provider settings.
<script lang="ts">
import {
ConfigProvider,
DatePicker,
Form,
FormItem,
RadioGroup,
RangePicker,
TimePicker,
TimeRangePicker,
createForm
} from '@woodger/antd';
const form = createForm({ initialValues: {} });
let suffix = $state('default');
const suffixIcon = $derived(
suffix === 'custom'
? customSuffix
: suffix === 'none'
? null
: undefined
);
</script>
{#snippet customSuffix()}<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
><circle
cx="10"
cy="10"
r="6"
/><path
d="m15 15 5 5"
/></svg>{/snippet}
<div class="settings">
<RadioGroup aria-label={("Date and time suffix")} bind:value={suffix}
options={([
{ value: 'default', label: "Default" }, { value: 'custom', label: "Own icon" }, {
value: 'none',
label: "Without icon"
}
])} />
</div>
<ConfigProvider datePicker={{ suffixIcon }} timePicker={{ suffixIcon }}>
<Form {form} aria-label={("Date and time icons")}>
<FormItem
label="DatePicker (suffixIcon=true)"
htmlFor="feedback-date"
validateStatus="success"
hasFeedback
>
<DatePicker
id="feedback-date"
aria-label="DatePicker feedback"
suffixIcon={true}
style="width:100%"
/>
</FormItem>
<FormItem label="RangePicker" htmlFor="feedback-range" validateStatus="warning" hasFeedback>
<RangePicker id="feedback-range" aria-label="RangePicker feedback" style="width:100%" />
</FormItem>
<FormItem label="TimePicker" htmlFor="feedback-time" validateStatus="error" hasFeedback>
<TimePicker id="feedback-time" aria-label="TimePicker feedback" style="width:100%" />
</FormItem>
<FormItem
label="TimeRangePicker"
htmlFor="feedback-time-range"
validateStatus="validating"
hasFeedback
>
<TimeRangePicker
id="feedback-time-range"
aria-label="TimeRangePicker feedback"
style="width:100%"
/>
</FormItem>
</Form>
</ConfigProvider>
<style>
.settings { margin-bottom: 24px; }
</style>
Custom validation icons
Form.feedbackIcons sets form icons. hasFeedback.icons replaces the field renderer; false hides an error icon while retaining its message.
<script lang="ts">
import { Button, Form, FormItem, Input, createForm, type FormFeedbackIcons } from '@woodger/antd';
const form = createForm({ initialValues: { shared: 'woodger', local: 'Svelte' } });
const feedbackIcons: FormFeedbackIcons = ({ status }) => ({
[status]: status === 'success'
? sharedSuccess
: status === 'error'
? sharedError
: undefined
});
</script>
{#snippet sharedSuccess()}<span
class="shared-feedback"
><svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
><path
d="m5 12 4 4L19 6"
/></svg></span>{/snippet}
{#snippet sharedError()}<span
class="shared-feedback"
><svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
><path
d="m6 6 12 12M6 18 18 6"
/></svg></span>{/snippet}
{#snippet localSuccess()}<span
class="local-feedback"
><svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
aria-hidden="true"
><circle
cx="12"
cy="12"
r="10"
/><path
d="m6 12 4 4 8-8"
/></svg></span>{/snippet}
<Form {form} {feedbackIcons} aria-label={("Custom Form icons")}>
<FormItem name="shared" label={("Form icons")} hasFeedback
rules={([{ required: true, message: "Fill in the field with the form icon." }])}>
<Input value={form.values.shared} onValueChange={value => form.setFieldValue(
'shared',
value ?? ''
)} />
</FormItem>
<FormItem name="local" label={("Field icons")} hasFeedback={{
icons: () => ({
success: localSuccess,
error: false
})
}}
rules={([{ required: true, message: "Fill in the field with the local icon." }])}>
<Input value={form.values.local} onValueChange={value => form.setFieldValue(
'local',
value ?? ''
)} />
</FormItem>
<div class="actions">
<Button htmlType="submit" type="primary">{("Validate fields with icons")}</Button>
<Button htmlType="reset">{("Reset fields with icons")}</Button>
</div>
</Form>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
Initial field values
Priority of initialValues, FormItem.initialValue and new default for next reset.
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm<{ primary: string; local?: string }>({
initialValues: {
primary: "From the mold"
}
});
let seed = $state(("From the field"));
</script>
<style>
.settings {
display: grid;
gap: 8px;
margin-bottom: 24px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
<div class="settings">
<label
for="form-docs-initial-seed"
>{("Initial value for next reset")}</label>
<Input
id="form-docs-initial-seed"
value={seed}
onValueChange={value => { seed = value ?? ''; }}
/>
</div>
<Form {form} aria-label={("Initial field values")}>
<FormItem name="primary" label={("Priority initialValues")} initialValue={("This value will not replace the form")}>
<Input value={form.values.primary} onValueChange={value => form.setFieldValue(
'primary',
value ?? ''
)} />
</FormItem>
<FormItem name="local" label={("InitialValue of a separate field")} initialValue={seed}>
<Input value={form.values.local ?? ''} onValueChange={value => form.setFieldValue(
'local',
value ?? ''
)} />
</FormItem>
<div class="actions">
<Button
onclick={() => form.setFieldsValue({ primary: "Changed", local: "Draft" })}
>{("Change initial fields")}</Button>
<Button htmlType="reset">{("Reset initial fields")}</Button>
<Button
onclick={() => form.resetFields(['local'])}
>{("Reset local field")}</Button>
</div>
</Form>
transform, len and whitespace
Convert for rule only, string/array length and check for non-empty string of spaces.
<script lang="ts">
import { Button, CheckboxGroup, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { code: ' ABCD ', note: '', roles: ["Reading"] } });
let submitted = $state('');
</script>
<style>
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("Transformation and exact restrictions")}
onFinish={values => { submitted = JSON.stringify(values); }}>
<FormItem name="code" label={("Four character code")}
extra={("Trim applies only to the rule: spaces are kept in the model.")}
rules={([{
transform: value => typeof value === 'string' ? value.trim() : value,
len: 4, message: "After trim you need exactly four characters."
}])}>
<Input
value={form.values.code}
onValueChange={value => form.setFieldValue('code', value ?? '')}
/>
</FormItem>
<FormItem name="note" label={("Note without any spaces")}
extra={("An empty optional value is acceptable.")}
rules={([{
whitespace: true,
message: "The note should not consist only of spaces."
}])}>
<Input
value={form.values.note}
onValueChange={value => form.setFieldValue('note', value ?? '')}
/>
</FormItem>
<FormItem name="roles" label={("Exactly two roles")}
rules={([{ len: 2, message: "Select exactly two roles." }])}>
<CheckboxGroup options={(["Reading", "Record", "Publication"])} value={form
.values.roles}
onValueChange={value => form.setFieldValue('roles', value)} />
</FormItem>
<Button htmlType="submit" type="primary">{("Check restrictions")}</Button>
</Form>
<output aria-label={("Original value before transform")}>{JSON.stringify(
form.values.code
)}</output>
<output aria-label={("Form rules result")}>{(submitted
|| ("Not shipped yet"))}</output>
Procedure for checking rules
All messages, sequential stop and first completed error; call counters.
<script lang="ts">
import {
Button,
Form,
FormItem,
FormValidationError,
Input,
RadioGroup,
createForm
} from '@woodger/antd';
const form = createForm({ initialValues: { name: "Value to be checked" } });
let mode = $state<'all' | 'serial' | 'parallel'>('all');
let first = $state(0);
let second = $state(0);
const rules = [
{ validator: () => { first++; return "The first rule is rejected."; } },
{ validator: () => { second++; return "The second rule is rejected."; } }
];
async function check() {
first = 0;
second = 0;
try {
await form.validateFields();
}
catch (error) {
if (!(error instanceof FormValidationError)) {
throw error;
}
}
}
</script>
<style>
.settings { margin-bottom: 24px; }
output {
display: block;
margin-top: 16px;
}
</style>
<div
class="settings"
><RadioGroup
aria-label={("Procedure for checking rules")}
bind:value={mode}
options={([
{ value: 'all', label: "All rules" }, { value: 'serial', label: "First in order" },
{ value: 'parallel', label: "First completed" }
])}
/></div>
<Form {form} aria-label={("ValidateFirst mode")}>
<FormItem name="name" label={("Value for validateFirst")} rules={(rules)}
validateFirst={mode === 'all' ? false : mode === 'serial' ? true : 'parallel'}>
<Input
value={form.values.name}
onValueChange={value => form.setFieldValue('name', value ?? '')}
/>
</FormItem>
<Button
onclick={() => { void check(); }}
>{("Run validateFirst rules")}</Button>
</Form>
<output
aria-label={("Calls to validateFirst rules")}
>{("First: ")}{first}{("; second: ")}{second}</output>
Delayed field validation
validateDebounce delays automatic verification; submit checks immediately.
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { name: '' } });
let calls = $state(0);
const rules = [{
validator: (value: unknown) => {
calls++;
return typeof value === 'string' && value.length >= 3
? undefined
: "At least three characters are required.";
}
}];
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
}
</style>
<Form {form} aria-label={("Delayed automatic check")}>
<FormItem
name="name"
label={("Name with debounce 500 ms")}
rules={(rules)}
validateDebounce={500}
extra={("After the first blur, change the name: automatic verification waits for a pause. Submit checks immediately.")}
>
<Input
value={form.values.name}
onValueChange={value => form.setFieldValue('name', value ?? '')}
/>
</FormItem>
<div class="actions">
<Button htmlType="submit">{("Check immediately")}</Button>
<Button htmlType="reset">{("Reset check")}</Button>
</div>
</Form>
<output aria-label={("Deferred validator calls")}>{calls}</output>
Scrolling and ref fields
scrollToField, getFieldInstance, scrollToFirstError and separate focus inclusion.
<script lang="ts">
import { Button, Checkbox, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { name: "Anna", email: '' } });
let area = $state<HTMLDivElement>();
let focus = $state(false);
let instance = $state(("Not requested yet"));
</script>
<style>
.settings,
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
margin-bottom: 20px;
}
.area {
height: 230px;
margin-block-end: 16px;
overflow: auto;
padding: 16px;
border: 1px solid var(--ant-color-border);
border-radius: 8px;
}
.gap { height: 260px; }
output {
display: block;
margin-top: 16px;
}
</style>
<div class="settings">
<Checkbox bind:checked={focus}>
{("Focus error after scrolling")}
</Checkbox>
</div>
<div class="actions">
<Button onclick={() => form.scrollToField('email', {
boundary: area,
block: 'center',
focus: true
})}>{("Go to email")}</Button>
<Button onclick={() => {
instance = form.getFieldInstance('email')
? ("Ref registered")
: ("Control not yet mounted");
}}>{("Get ref email")}</Button>
</div>
<Form {form} aria-label={("Scroll to form field")}
scrollToFirstError={{ boundary: area, block: 'center', focus }}>
<div class="area" bind:this={area}>
<FormItem name="name" label={("Name in scrollable form")}>
<Input value={form.values.name} onValueChange={value => form.setFieldValue(
'name',
value ?? ''
)} />
</FormItem>
<div class="gap" aria-hidden="true"></div>
<FormItem name="email" label={("Email in scrollable form")}
rules={([{ required: true, message: "Fill in your email at the bottom of the area." }])}>
<Input value={form.values.email} onValueChange={value => form.setFieldValue(
'email',
value ?? ''
)} />
</FormItem>
</div>
<Button htmlType="submit">{("Check and scroll")}</Button>
</Form>
<output aria-label={("Registration ref fields")}>{instance}</output>
Rule value types
Explicit integer, float and boolean; the string does not automatically become a number.
<script lang="ts">
import { Button, Form, FormItem, Input, InputNumber, Switch, createForm } from '@woodger/antd';
const form = createForm<{ amount: string | number; fraction: number | null; enabled: boolean }>({
initialValues: { amount: '12', fraction: 1.5, enabled: false }
});
let result = $state('');
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("Rule value types")}
onFinish={values => { result = JSON.stringify(values); }}
onFinishFailed={() => { result = ("Correct the value type."); }}>
<FormItem name="amount" label={("Integer")}
extra={("Input writes a string. The conversion is performed by a separate button, not a rule.")}
rules={([{
type: 'integer',
required: true,
message: "You need an integer number, the string is not suitable."
}])}>
<Input aria-label={("Integer")} value={String(form.values.amount)}
onValueChange={value => form.setFieldValue('amount', value ?? '')} />
</FormItem>
<FormItem name="fraction" label={("Fractional number")}
extra={("Float rejects integers.")}
rules={([{
type: 'float',
required: true,
message: "You need a fractional number, for example 1.5."
}])}>
<InputNumber aria-label={("Fractional number")} value={form.values.fraction} step={0.5}
onValueChange={value => form.setFieldValue('fraction', value)} />
</FormItem>
<FormItem name="enabled" label={("Boolean value")}
extra={("Required accepts false. A validator is required to agree to the terms.")}
rules={([{ type: 'boolean', required: true }])}>
<Switch aria-label={("Boolean value")} checked={form.values.enabled}
onCheckedChange={value => form.setFieldValue('enabled', value)} />
</FormItem>
<div class="actions">
<Button htmlType="submit">{("Check types")}</Button>
<Button onclick={() => {
form.setFieldValue('amount', Number(form.values.amount));
result = '';
}}>{("Convert to number")}</Button>
</div>
</Form>
<output aria-label={("Value type in the model")}>amount: {(typeof form.values.amount)}</output>
<output aria-label={("Type check result")}>{(result
|| ("Not verified yet"))}</output>
Formats, enum and pattern
Email, URL, HEX, phone, strict enumeration and string pattern.
<script lang="ts">
import { Button, Form, FormItem, Input, Select, createForm } from '@woodger/antd';
const form = createForm({
initialValues: {
email: 'wrong',
url: 'wrong',
hex: 'wrong',
tel: 'wrong',
role: 'guest',
code: 'a'
}
});
let result = $state('');
const formats = [
{ name: 'email', label: "Email for verification", type: 'email' },
{ name: 'url', label: "Website address", type: 'url' },
{ name: 'hex', label: "HEX color", type: 'hex' },
{ name: 'tel', label: "Phone for verification", type: 'tel' }
] as const;
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
}
</style>
<Form {form} aria-label={("Formats and enumeration")}
onFinish={() => { result = ("All formats are acceptable."); }}
onFinishFailed={() => { result = ("Correct the format of the fields."); }}>
{#each formats as field (field.name)}
<FormItem name={field.name} label={(field.label)}
rules={([{
type: field.type,
required: true,
message: "${label}: invalid format."
}])}>
<Input aria-label={(field.label)} value={form.values[field.name]}
onValueChange={value => form.setFieldValue(field.name, value ?? '')} />
</FormItem>
{/each}
<FormItem name="role" label={("Allowed role")} extra={("Guest is in the list, but is prohibited by the enum rule.")}
rules={([{
type: 'enum',
enum: ['reader', 'editor'],
message: "Select reader or editor."
}])}>
<Select aria-label={("Allowed role")} value={form.values.role}
options={(['guest', 'reader', 'editor'].map(
value => ({ value, label: value })
))}
onValueChange={value => form.setFieldValue('role', value ?? '')} />
</FormItem>
<FormItem name="code" label={("Two capital letter code")}
rules={([{
type: 'string',
pattern: '^[A-Z]{2}$',
message: "Two letters A–Z are needed."
}])}>
<Input aria-label={("Two capital letter code")} value={form.values.code}
onValueChange={value => form.setFieldValue('code', value ?? '')} />
</FormItem>
<div class="actions">
<Button htmlType="submit">{("Check formats")}</Button>
<Button onclick={() => {
form.setFieldsValue({
email: 'reader@example.org', url: 'https://woodger.org',
hex: '#52c41a', tel: '+12025550123', role: 'reader', code: 'AB'
});
result = '';
}}>{("Substitute correct values")}</Button>
</div>
</Form>
<output aria-label={("Format check result")}>{(result
|| ("Not verified yet"))}</output>
Rule factories
Synchronous rule from the current FormInstance, without side effects.
<script lang="ts">
import {
Button,
Form,
FormItem,
Input,
InputNumber,
createForm,
type FormRule
} from '@woodger/antd';
const form = createForm({ initialValues: { minimum: 4, code: 'ab' } });
const rules: readonly FormRule[] = [
current => {
const minimum = Number(current.getFieldValue('minimum'));
return {
type: 'string', required: minimum > 0, min: minimum,
message: "${label}: minimum ${min} symbol."
};
}
];
let result = $state('');
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<Form {form} aria-label={("Rule factories")}
onFinish={() => { result = ("The current rule is satisfied."); }}
onFinishFailed={() => { result = ("The check used the current minimum."); }}>
<FormItem name="minimum" label={("Minimum characters")}>
<InputNumber aria-label={("Minimum characters")} min={0} max={8} value={form.values
.minimum}
onValueChange={value => form.setFieldValue('minimum', value ?? 0)} />
</FormItem>
<FormItem name="code" label={("Code according to the current rule")} rules={(rules)}
extra={("Factory synchronous and clean: reads the model when checking and calculating the obligation.")}>
<Input aria-label={("Code according to the current rule")} value={form.values.code}
onValueChange={value => form.setFieldValue('code', value ?? '')} />
</FormItem>
<Button htmlType="submit">{("Check current rule")}</Button>
</Form>
<output aria-label={("Rule factory result")}>{(result
|| ("Not verified yet"))}</output>
Nested object and array rules
fields and defaultField check the contents of the same parent binding.
<script lang="ts">
import { Button, Form, FormItem, Input, Select, createForm } from '@woodger/antd';
const form = createForm({
initialValues: { profile: { name: 'A', age: 15 }, recipients: ['wrong'] }
});
let result = $state('');
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
overflow-wrap: anywhere;
}
</style>
<Form {form} aria-label={("Nested rules")}
onFinish={() => { result = ("The object and array elements passed the test."); }}
onFinishFailed={() => { result = ("Errors are collected from parent fields."); }}>
<FormItem name="profile" label={("Profile object")}
extra={("One binding profile; the name and age rules do not create separate fields.")}
rules={([{
type: 'object', required: true, fields: {
name: { type: 'string', min: 2, message: "Profile name: minimum 2 characters." },
age: { type: 'integer', min: 18, message: "Profile age: from 18 years." }
}
}])}>
<Input aria-label={("Profile object")} readOnly value={JSON.stringify(
form.values.profile
)} />
</FormItem>
<FormItem name="recipients" label={("Recipients")}
extra={("DefaultField checks each element of the array.")}
rules={([{
type: 'array', required: true,
defaultField: { type: 'email', message: "Recipient ${name}: email required." }
}])}>
<Select mode="multiple" aria-label={("Recipients")} value={form.values.recipients}
options={(['wrong', 'one@example.org', 'two@example.org'].map(value => ({
value,
label: value
})))}
onValueChange={value => form.setFieldValue('recipients', value)} />
</FormItem>
<div class="actions">
<Button htmlType="submit">{("Check nested rules")}</Button>
<Button onclick={() => {
form.setFieldsValue({ profile: { name: "Anna", age: 24 }, recipients: ['one@example.org'] });
result = '';
}}>{("Fix object and array")}</Button>
</div>
</Form>
<output aria-label={("Result of nested rules")}>{(result
|| ("Not verified yet"))}</output>
Message variables
Substitution of label/min and own hint for rich label.
<script lang="ts">
import { Button, Checkbox, Form, FormItem, Input, createForm } from '@woodger/antd';
const form = createForm({ initialValues: { code: 'ab' } });
let alias = $state(true);
</script>
<style>
.settings { margin-bottom: 24px; }
</style>
{#snippet label()}<strong>{("Invitation code")}</strong>{/snippet}
<div
class="settings"
><Checkbox
bind:checked={alias}
>{("Clear label in the message")}</Checkbox></div>
<Form {form} aria-label={("Message variables")}>
<FormItem name="code" label={(label)}
messageVariables={(alias ? {
label: "Invitation",
hint: "No spaces."
} : { hint: "No spaces." })}
rules={([
{ type: 'string', min: 4, message: "${label}: minimum ${min}. ${hint}" }
])}>
<Input aria-label={("Invitation code")} value={form.values.code}
onValueChange={value => form.setFieldValue('code', value ?? '')} />
</FormItem>
<Button htmlType="submit">{("Check message variables")}</Button>
</Form>
Message templates
Priority of rule, form, provider and locale; replacing a nested group of patterns.
<script lang="ts">
import {
Button, Checkbox, ConfigProvider, Form, FormItem, Input, createForm, ruRU,
type ValidateMessages
} from '@woodger/antd';
const form = createForm({ initialValues: { name: '', code: 'a', note: '123456', fixed: '' } });
let local = $state(true);
const messages: ValidateMessages = {
required: "Form: fill in ${label}.",
string: { min: "Form: ${label}, minimum ${min}." }
};
</script>
<style>
.settings { margin-bottom: 24px; }
</style>
<div
class="settings"
><Checkbox
bind:checked={local}
>{("Local form templates")}</Checkbox></div>
<ConfigProvider
locale={{
...ruRU, Form: {
...ruRU.Form,
defaultValidateMessages: ({ required: "Locale: fill in ${label}." })
}
}}
form={{
validateMessages: ({
required: "Provider: fill in ${label}.",
string: {
min: "Provider: ${label}, minimum ${min}.",
max: "Provider: ${label}, maximum ${max}."
}
})
}}>
<Form {form} aria-label={("Message templates")} validateMessages={(local ? messages : undefined)}>
<FormItem name="name" label={("Template name")} rules={([{
required: true
}])}>
<Input aria-label={("Template name")} value={form.values.name}
onValueChange={value => form.setFieldValue('name', value ?? '')} />
</FormItem>
<FormItem name="code" label={("Short code")} rules={([{
type: 'string',
min: 4
}])}>
<Input aria-label={("Short code")} value={form.values.code}
onValueChange={value => form.setFieldValue('code', value ?? '')} />
</FormItem>
<FormItem
name="note"
label={("Long note")}
rules={([{ type: 'string', max: 3 }])}
extra={("The local group string replaces the entire provider group. For max, inline text is included.")}
>
<Input aria-label={("Long note")} value={form.values.note}
onValueChange={value => form.setFieldValue('note', value ?? '')} />
</FormItem>
<FormItem name="fixed" label={("Own message")}
rules={([{ required: true, message: "Rule: fill in ${label}." }])}>
<Input aria-label={("Own message")} value={form.values.fixed}
onValueChange={value => form.setFieldValue('fixed', value ?? '')} />
</FormItem>
<Button htmlType="submit">{("Check message templates")}</Button>
</Form>
</ConfigProvider>
Form and FormItem choose prefixes independently. FormList.prefixCls refers to the ErrorList, not the adjacent fields. Adaptive captions respect the screen*Max tokens of their topic area; changing the prefix preserves the model and rules.
Form CSS prefixes
Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.
<script lang="ts">
import { Checkbox, ConfigProvider, Form, FormItem, Input, Button, createForm } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-form' : '');
const form = createForm({ initialValues: { name: "Draft form" } });
let submitted = $state('—');
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("Common prefix Form suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Local prefix Form")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'form-theme' } }}>
<div class="prefix-stage">
<Form {form} prefixCls={localPrefix} layout="horizontal" aria-label={("Form with prefix")}
labelCol={{ xs: 24, sm: 8 }} wrapperCol={{ xs: 24, sm: 16 }}
onFinish={values => { submitted = values.name; }}>
<FormItem prefixCls={local ? 'project-field' : ''} name="name" label={("Name")}
rules={([{ required: true, message: "Enter a name." }])}>
<Input value={form.values.name} onValueChange={value => form.setFieldValue('name', value)}
aria-label={("Form name with prefix")} />
</FormItem>
<div class="controls">
<Button
htmlType="submit"
type="primary"
>{("Submit form with prefix")}</Button>
<Button htmlType="reset">{("Reset form with prefix")}</Button>
</div>
</Form>
<output aria-label={("Sent Form with prefix")}>{submitted}</output>
</div>
</ConfigProvider>
<output aria-label={("CSS prefix Form")}>{("General: ")}{prefix}{("; local: ")}{(localPrefix
|| ("from the provider"))}</output>
<p>
{("Form and FormItem choose prefixes independently. FormList.prefixCls refers to the ErrorList, not the adjacent fields. Adaptive captions respect the screen*Max tokens of their topic area; changing the prefix preserves the model and rules.")}
</p>
</div>
API
Themes are checked against the official Form Ant Design 6.7.0 page and public types @woodger/antd. React Form.Item and createForm have different contracts: Below is the actual available Svelte API.
| Theme | Example or limitation |
|---|---|
| Basic Usage | Labels, rules, sending and reset. |
| Form methods | Explicit methods of the createForm model. |
| resetFields | Selective and full reset, exact NamePath, re-creation of field and list contents. |
| GetFieldsValue / FilterFunc | Projection bindings, entire store, path list, nullable metadata filter and FormList roots. |
| Set fields status | Batch values, errors/warnings, touched and manual validating without automatic validation. |
| Form Layout | vertical/horizontal/inline; default is vertical. |
| Form mix layout | FormItem.layout specifies the location of an individual field. |
| Form disabled | Context for disabling @woodger/antd controls. |
| Form variants | General variant of fields via Form.variant with local exceptions. |
| No DOM wrapper | component=false passes the context without an embedded HTML form. |
| Required style | requiredMark: true/false/optional and your own snippet; the rules remain independent. |
| Form size | Size of controls via Form.size with local exceptions. |
| label can wrap | responsive labelCol/wrapperCol, labelAlign, labelWrap and label:null. |
| No block rule | warningOnly shows a warning about the short name and does not block validation or submission. |
| Watch Hooks | The reactive value from Form.useWatch() is the value at a path or the result of a selector. |
| Validate Trigger | Form.validateTrigger sets the default validation events. FormItem.validateTrigger configures them for an individual field. |
| Validate Only | Silent checking, recursive path selection and dirty filter taking into account initial values. |
| Path Prefix | NamePath supported; automatic prefix is given by FormList. There is no arbitrary HOC prefix. |
| Dynamic Form Item | FormList: add with insertIndex, remove, move, local rules and list errors. |
| Dynamic Form nest Items | Object strings with the relative name FormItem and the full path of the model. |
| Drag sorting | move saves row key; example uses a button. Drag and drop is not built in. |
| Complex Dynamic Form Item | Nested FormList, initialValue and reset of teams and participants. |
| Nest | A segment array accesses a nested object; the line with the dot remains one key. |
| complex form control | Nameless layout and clean noStyle bindings with error collection. |
| Customized Form Controls | value/callback of the own component and FormItem context. |
| Store Form Data into Upper Component | fields supplies values and metadata from an external model. onFieldsChange reports control edits and validation changes. |
| Control between forms | Form.Provider groups named forms and reports changes and submissions. |
| Inline Login Form | inline mode and local axis of a separate field. |
| Login Form | Email/password fields and rules checking. |
| Registration | Password confirmation via validator(value, values). |
| Advanced search | CSS grid and conditional FormItem; hidden values are preserved. |
| Form in Modal to Create | Native form/id and explicit reset on opening. |
| Time-related Controls | Dayjs directly into the model. |
| Handle Form Data Manually | setFieldValue/setFieldsValue without mutation values. |
| Customized Validation | validator returns a message or Promise. |
| Dynamic Rules | Reactive FormItem.rules and explicit double-check via touchField. |
| Dependencies | dependencies sets the field paths whose control edits can trigger revalidation. |
| getValueProps + normalize | Transformation in the owner handler, without props of the same name. |
| Slide to error field | getFieldInstance/focusField/scrollToField and scrollToFirstError; focus is turned on separately. |
| Other Form Controls | checked for Switch and number for InputNumber. |
| Hidden | Hidden binding saves value and validation. |
| FeedbackIcons | Form defaults, local snippets and hiding an individual icon. |
| Validation feedback | hasFeedback for input, selection and dates; visual status is separate from rules. |
| Form.Item.useStatus | useFormItemStatus returns reactive readonly getter fields. |
| Initial values | Priority of form and field defaults, reset with new initialValue. |
| Validation rules | transform, exact length len and whitespace. |
| Validate First | All rules, sequential stop and first completed error. |
| Validate Debounce | Auto check delay without submit delay. |
| Rich labels and help | Snippet labels, tooltip, available names, help and extra. |
| Custom semantic dom styling | Object and functional slots, ConfigProvider.form, rootClassName/style. |
| Rule value types | Explicit integer, float and boolean; the string does not automatically become a number. |
| Formats, enum and pattern | Email, URL, HEX, phone, strict enumeration and string pattern. |
| Rule factories | Synchronous rule from the current FormInstance, without side effects. |
| Nested object and array rules | fields and defaultField check the contents of the same parent binding. |
| Message variables | Substitution of label/min and own hint for rich label. |
| Message templates | Priority of rule, form, provider and locale; replacing a nested group of patterns. |
Form
| Property | Description | Type | Default |
|---|---|---|---|
prefixCls | Full native Form prefix. FormItem and FormList select prefixes separately; local Form.prefixCls does not rename them. The empty string/undefined inherit ConfigProvider. | string | ConfigProvider.prefixCls + "-form" |
validateMessages | Built-in error templates. rule.message takes precedence; the nested Form group replaces the entire provider group. | ValidateMessages | ConfigProvider.form / locale.Form |
form | Pass the model from Form.useForm() or createForm to access it externally. | FormInstance<Values> | internal model |
fields | External values and metadata are applied after mount without calling onFieldsChange. | readonly FormFieldData[] | — |
onFieldsChange | Reports field changes from control edits and validation. | (changedFields, allFields) => void | — |
validateTrigger | Default events for automatic field validation. Accepts a string, an array, or false. | FormValidateTrigger | onChange |
children | Form fields and actions. | Snippet | is required |
layout | General location; FormItem.layout can clarify the field axis. | vertical | horizontal | inline | vertical |
disabled | Defaults child controls; the closest provider and local disabled take precedence. Sending blocks repeated actions. | boolean | ConfigProvider.componentDisabled |
variant | Option for the fields of the nearest Form. Takes precedence over component settings and the general ConfigProvider.variant, but is inferior to the local variant of the field. undefined does not inherit the variant of the outer Form. | Variant | undefined |
component | false leaves the context without a DOM wrapper, submit/reset and DOM attributes. | 'form' | false | form |
onFinish | After successful verification. Promise holds isSubmitting. | (values: Values) => void | Promise<void> | — |
onFinishFailed | Rule errors; outOfDate is a legacy check. | (error: FormValidationError<Values>) => void | — |
onError | Error in onFinish execution, separate from validation. | (error: unknown) => void | — |
class | Class of present form; native id, style and aria attributes are also available. | string | — |
size | Size of child controls; local size and closest provider take precedence. | ComponentSize | Form / ConfigProvider |
colon | Colon horizontal label; local FormItem.colon takes precedence. | boolean | ConfigProvider.form / true |
labelAlign | Label alignment; FormItem can refine it. | left | right | ConfigProvider.form / right |
labelWrap | Transferring labels inside selected columns. | boolean | ConfigProvider.form / false |
labelCol | Adaptive label and control columns; a local Item object replaces the entire global one. | ColProps | — |
requiredMark | Visual mark only. Snippet gets label and { required }; the rules don't change. | boolean | 'optional' | FormRequiredMark renderer | ConfigProvider.form / true |
feedbackIcons | The ({ status, errors, warnings }) renderer returns icons by status. FormItem.hasFeedback enables them; a local icons renderer takes priority. | FormFeedbackIcons | — |
tooltip | Tooltips Defaults; The icon appears only when the tooltip field is specified. | FormTooltipProps | ConfigProvider.form.tooltip |
scrollToFirstError | true scrolls without focus, false disables action; object supports focus. Fires after onFinishFailed. | boolean | FormScrollOptions | ConfigProvider.form / native autofocus |
rootClassName | Additional class native form; component=false does not create root. | string | — |
classNames | Object or callback; root/label/content/help/helpItem/extra. styles - CSS strings. | FormSemantic | ConfigProvider.form |
wrapperCol | Speakers control; Nested Items do not inherit from the outer Item. | ColProps | — |
styles | CSS lines by slots; local style overrides semantic root. | FormSemantic | ConfigProvider.form.styles |
FormItem
| Property | Description | Type | Default |
|---|---|---|---|
prefixCls | The full base Form prefix of the field (the Item class adds -item). Resolved regardless of Form.prefixCls; empty string/undefined inherit ConfigProvider. | string | ConfigProvider.prefixCls + "-form" |
messageVariables | Substitutions in messages: label/name and rule parameters. Only the text is overridden, not the restrictions; for a rich label, set the string label explicitly. | Readonly<Record<string, string>> | {} |
name | Without name only layout: without model binding, rules and native name. In the list, the name is relative to the FormList. | NamePath | — |
label | Text, number, array or snippet. null stores the offset of the columns; false/undefined/empty string hide the label without this offset. | RenderEmptyContent | — |
children | Control; value/checked and callback are passed explicitly. | Snippet | is required |
help | Rich explanation instead of missing errors/warnings; reset recreates the content. | RenderEmptyContent | — |
required | Marker and sign of mandatory control; does not add a validation rule. | boolean | by rules.required |
rules | ValidationRule objects or pure synchronous factories (form) => ValidationRule; priority over createForm.rules. An empty array disables model rules; when unmount, local rules are removed, the value is saved. | readonly FormRule[] | model rules |
htmlFor | Explicit control identifier for label. | string | generated id |
class | FormItem external container class. | string | — |
extra | Constant rich explanation next to errors/warnings; is associated with control and is recreated when reset. | RenderEmptyContent | — |
initialValue | Fills undefined before render. initialValues of the form takes precedence; the prop change is used by the future reset. | unknown | — |
hidden | Hides the block, preserving the control, value and registration of the rules. | boolean | false |
noStyle | Pure binding without layout; errors are collected by the nearest styled Item. help=false disables message transmission. | boolean | false |
layout | Local field location. Standalone Item defaults to vertical. | horizontal | vertical | Form.layout |
labelAlign | Local label alignment. | left | right | Form.labelAlign |
labelCol | Replaces the generic object including {}. | ColProps | Form.labelCol |
wrapperCol | Replaces a generic object; does not inherit from the outer FormItem. | ColProps | Form.wrapperCol |
colon | Explicit true includes the colon even when Form.colon=false. | boolean | Form.colon |
tooltip | Content or Tooltip object with icon-snippet; general defaults is set by Form.tooltip. | FormItemTooltip | — |
validateFirst | false collects all messages, true stops the rules in order, parallel selects the first error that completed. | boolean | 'parallel' | false |
validateTrigger | Events that validate the field automatically. With false or an empty array, validation still runs on submit and explicit calls. | FormValidateTrigger | Form.validateTrigger |
validateDebounce | Automatic validation delay in ms. validateFields and submit are fired immediately. | number | — |
hasFeedback | Icon for the current status. false from the renderer hides it; null/undefined/an empty string/0 use the default. noStyle inherits the icon unless hasFeedback is explicitly set. | boolean | { icons?: FormFeedbackIcons } | false |
validateStatus | Visual status; an empty line disables automatic. Errors and aria-invalid are not cleared. | FormValidateStatus | by metadata |
controlRef | An explicit DOM/ref with focus/nativeElement takes precedence and is returned by getFieldInstance without a wrapper. | unknown | registration control |
rootClassName | Additional layout-root class. | string | — |
style | root CSS after component tokens; noStyle without hidden does not create a layout. | string | — |
createForm
| Property | Description | Type | Default |
|---|---|---|---|
initialValues | Initial values, including nested objects and arrays. Optional fields may be missing; the model type is specified by createForm<values>. | Values | is required |
rules | Top level rules; work without FormItem in the DOM. For nested fields, use FormItem.rules. | FormRules<Values> | {} |
FormInstance
| Property | Description | Type | Default |
|---|---|---|---|
values | Reactive values; change via setters, do not bind:value to values. | Readonly<Values> | copy of initialValues |
errors | Top level errors; nested errors are read via getFieldError/getFieldsError. | Readonly<FieldErrors<Values>> | {} |
isSubmitting | Check/submit; resubmit returns busy. | boolean | false |
submissionError | Last callback sending error. | unknown | undefined |
getFieldValue | Full path value from root Form; the type of the known path is displayed, the type of the dynamic path is unknown. | (name: NamePath) => NamePathValue<Values, Path> | — |
getFieldsValue | Passing true or [[]] without a filter returns Values. Other calls return a projection that can omit nested fields and array entries. The FormGetFieldsValueConfig.filter callback receives FormFieldMeta | null. | FormInstance<Values>["getFieldsValue"] | bindings |
getFieldsError | Paths, errors and non-blocking warnings. | (names?: readonly NamePath[]) => FieldError[] | all fields |
getFieldError | Messages of one nested or root field. | (name: NamePath) => readonly string[] | — |
getFieldWarning | Messages warningOnly one field; are not included in errors. | (name: NamePath) => readonly string[] | — |
isFieldTouched | Considers the field itself and the path's known descendants; [] checks the entire model. The request does not change the metadata. | (name: NamePath) => boolean | — |
isFieldsTouched | Also accepts allTouched as a single argument. Without names, true requires all bindings except FormList roots. With names, true requires at least one touched field in each prefix group. | (names?: readonly NamePath[], allTouched?: boolean) => boolean | any field |
isFieldValidating | Flag of any binding with an exact name: regular validation or manual setFields.validating. The validateOnly flag is not included. | (name: NamePath) => boolean | — |
isFieldsValidating | Does the selected fields have validating, including the one specified via setFields. Names are exact, without descendants; [] does not select fields. The request does not change the metadata. | (names?: readonly NamePath[]) => boolean | all fields |
isFieldRequired | Availability of required in current local or model rules. | (name: NamePath) => boolean | — |
setFieldValue | Replace the full path value, including the entire object or array. | (name: NamePath, value) => void | — |
setFieldsValue | Recursively combine ordinary objects; Replace arrays and class instances entirely. | (next: PartialFormValues<Values>) => void | — |
setFields | Apply records in order without validation. value works without UI, metadata only for bindings. Changing value cancels the previous check. Manual field messages without rules do not by themselves block submit. | (fields: readonly FormFieldData[]) => void | — |
touchField | Check the box and run the test. | (name) => void | — |
resetFields | Restore the values of the selected paths; metadata is selected by its exact name. The contents of the selected FormItem and FormList rows are recreated. [] doesn't change anything; [[]] resets store without selecting metadata named fields. | (names?: readonly NamePath[]) => void | whole model |
validateFields | Also takes options as the first argument. The result contains the entire model; errors reject Promise. validateOnly does not change the messages; recursive and dirty filter fields. | (names?: readonly NamePath[], options?: FormValidateOptions) => Promise<Values> | all fields, flags false |
submit | success/invalid/failed/busy; native Form calls this method on submit. | (onFinish) => Promise<SubmissionResult<Values>> | — |
getFieldInstance | Ref mounted control; before mount and after removing undefined. The Instance type specifies the calling code. | <Instance = unknown>(name: NamePath) => Instance | undefined | — |
focusField | Delegates focus ref or associated native control. | (name: NamePath) => void | — |
scrollToField | Scroll to ref/native id; focus is turned on separately, the unknown field does nothing. | (name: NamePath, options?: FormScrollOptions) => void | — |
FormValidateOptions
| Property | Description | Type | Default |
|---|---|---|---|
validateOnly | No changes errors, warnings, touched and validating; saves messages already shown. Doesn't make the field dirty. | boolean | false |
recursive | Includes registered descendants of selected paths without re-checking for overlapping names. | boolean | false |
dirty | Changed, touched, previously checked fields and specified defaults, except undefined. reset clears history, but does not exclude defaults. | boolean | false |
FormFieldData
| Property | Description | Type | Default |
|---|---|---|---|
name | Full path from the model root; entries are applied in order. | NamePath | is required |
value | Replace value, including explicit undefined; works without binding. | unknown | save |
errors | Error messages. [] or undefined clears them; rules are not launched. | readonly string[] | save |
warnings | Warnings. [] or undefined clears them regardless of errors. | readonly string[] | save |
touched | Manual field marking; undefined is normalized to false. | boolean | save |
validating | Manual flag, including fields without rules. false also sets validated=true. | boolean | save; when changing value - false |
validated | Accepted, but does not replace the calculated flag; do not use to control validation. | boolean | is calculated |
FormFieldMeta
| Property | Description | Type | Default |
|---|---|---|---|
name | Segments of the selected registered field. | readonly (string | number)[] | way binding |
touched | Marked by blur, touchField, submit, or setFields. | boolean | false |
validating | Normal check or manual flag setFields; validateOnly doesn't change it. | boolean | false |
errors | Current messages, including manual ones. | readonly string[] | [] |
warnings | Current non-blocking warnings. | readonly string[] | [] |
validated | Completed normal validation, changed via setFieldsValue or explicit validating=false. validateOnly does not change the flag. | boolean | false |
FormList
| Property | Description | Type | Default |
|---|---|---|---|
prefixCls | Prefix of nested FormErrorList; empty string/undefined inherit ConfigProvider, adjacent FormItems are independent. | string | ConfigProvider.prefixCls + -form |
name | Path to array; in a nested list relative to the parent FormList. | NamePath | is required |
initialValue | Fills the missing array and participates in reset. The form's initialValues takes precedence, including []. | readonly unknown[] | — |
rules | Only custom validators with Svelte signature (value, values). Errors are output from meta.errors. | readonly FormListRule[] | — |
children | List markup without additional DOM wrapper. The key of each block each is field.key; Model bindings use the full path. | Snippet<[FormListFieldData[], FormListOperation, FormListMeta]> | is required |
FormListOperation
| Property | Description | Type | Default |
|---|---|---|---|
add | Add value and new key. An incorrect insertion index is also appended to the end. | (defaultValue?: unknown, insertIndex?: number) => void | to the end |
remove | Delete rows; duplicates and missing indexes do not remove neighbors. | (index: number | readonly number[]) => void | — |
move | Transfer value and key. Invalid and fractional indexes are ignored. | (from: number, to: number) => void | — |
FormListFieldData
| Property | Description | Type | Default |
|---|---|---|---|
name | Current row position for relative FormItem.name. | number | index |
key | String identity for keyed each; persists when move and neighbors are removed. | number | stable key |
FormListMeta
| Property | Description | Type | Default |
|---|---|---|---|
errors | List check messages; display them yourself next to the actions. | readonly string[] | [] |
warnings | Messages warningOnly list rules; do not block submit. | readonly string[] | [] |
FormListRule
| Property | Description | Type | Default |
|---|---|---|---|
validator | Array check; message on error, void on success. | (value, values) => string | void | Promise<string | void> | is required |
message | Public field of the rule. Custom validator returns its own message. | string | — |
warningOnly | Place the custom validator result in meta.warnings without blocking submission. | boolean | false |
FieldError
| Property | Description | Type | Default |
|---|---|---|---|
name | Source path segments; numeric and string indexes are different. | (string | number)[] | way |
errors | Field rules messages. | string[] | [] |
warnings | Messages warningOnly; in errorFields are transmitted along with errors for this field. | string[] | [] |
FormValidationError
| Property | Description | Type | Default |
|---|---|---|---|
values | Values at the start of the test. | Readonly<Values> | photo |
errorFields | Errors with full nested paths. | readonly FieldError[] | [] |
errors | Projection of top-level errors. | FieldErrors<Values> | {} |
outOfDate | Validation has become obsolete after changing, reset, deleting a field, or making a new call to validation, even a different field. Visible messages of individual fields are completed independently. | boolean | false |
ValidationRule
| Property | Description | Type | Default |
|---|---|---|---|
type | string, number, integer, float, boolean, array, object, date, regexp, method, any, enum, email, url, hex, tel or pattern. Store is not converted. Float rejects integers. | ValidationRuleType | implicit check |
enum | Allowed values for type:enum; strict comparison without type conversion. | readonly unknown[] | — |
fields | Child rules for type:object/array. Messages remain with the parent binding; individual fields are not registered. | Readonly<Record<string, ValidationRule | readonly ValidationRule[]>> | — |
defaultField | Rule for elements of array or other own keys of object. Nested factories are not supported. | ValidationRule | — |
required | Checks for an empty value. false and 0 are considered values. | boolean | false |
min | Minimum number or string/array length. | number | — |
max | Maximum number or length of string/array. | number | — |
pattern | String value pattern. | RegExp | string | — |
message | Own error text with substitutions ${variables}; priority over validateMessages. | string | message rules |
validator | Error message; void on success. With an explicit type, the custom validator replaces the built-in constraints. For consent, check true explicitly. | (value, values) => string | void | Promise<string | void> | — |
warningOnly | The message becomes a warning and does not block validateFields/submit or make the field required. | boolean | false |
len | The exact number, the number of Unicode code points of a string, or the length of an array. Takes precedence over min/max. | number | — |
whitespace | Rejects a non-empty string of all spaces; an empty optional value is acceptable. | boolean | false |
transform | Synchronous conversion for this rule only; is not written to store and is not passed on to the next rule. The exception becomes an error. | (value: FormValue) => FormValue | — |
ValidateMessages
| Property | Description | Type | Default |
|---|---|---|---|
default | General pattern of unknown restriction. ValidateMessage - string or () => string. | ValidateMessage | embedded text |
required | Required value; ${label} and ${name} are available. | ValidateMessage | embedded text |
enum | The value is outside the enumeration. | ValidateMessage | embedded text |
whitespace | A string of spaces. | ValidateMessage | embedded text |
types | Type and format errors: string, number, integer, float, boolean, array, object, method, regexp, date, email, tel, url, hex. | Partial<Record<type, ValidateMessage>> | {} |
string | String length patterns; the values are of type ValidateMessage. | { len?, min?, max?, range? } | {} |
number | Numerical restrictions. | { len?, min?, max?, range? } | {} |
array | Number of array elements. | { len?, min?, max?, range? } | {} |
date | Date errors. | { format?, parse?, invalid? } | {} |
pattern | Pattern mismatch. | { mismatch?: ValidateMessage } | {} |
FormErrorList
| Property | Description | Type | Default |
|---|---|---|---|
errors | Error messages, including strings, numbers and Svelte snippets. | readonly RenderEmptyContent[] | [] |
warnings | Warnings shown after errors. | readonly RenderEmptyContent[] | [] |
help | Replaces errors/warnings for any value other than null/undefined, including false, 0, and the empty string. | RenderEmptyContent | undefined |
helpStatus | status class for help: success, warning, error, validating or empty string. | FormValidateStatus | undefined |
fieldId | Sets the container id <fieldId>_help for explicit association with the field. | string | — |
class | Message container class; in the list its prefixCls is inherited. | string | — |
onVisibleChanged | After appearing or hiding. Not called for an initial empty list and after unmount. | (visible: boolean) => void | — |
useFormItemStatus()
| Property | Description | Type | Default |
|---|---|---|---|
status | readonly getter; empty string for pristine Item. Read through the object, destructuring creates a snapshot. | FormValidateStatus | undefined | undefined outside Item |
errors | Reactive messages of the nearest FormItem. | readonly string[] | [] |
warnings | Non-blocking warnings of the nearest FormItem. | readonly string[] | [] |
FormScrollOptions
| Property | Description | Type | Default |
|---|---|---|---|
block | Vertical alignment. | ScrollLogicalPosition | nearest |
inline | Horizontal alignment. | ScrollLogicalPosition | nearest |
scrollMode | Scroll only when necessary or always. | 'if-needed' | 'always' | if-needed |
boundary | Boundary for traversing scroll containers. | Element | ((parent: Element) => boolean) | — |
behavior | Native behavior or callback of calculated actions; Promise callback is not expected. | ScrollBehavior | ((actions) => unknown) | auto |
focus | Call focusField after scrolling. The scroll calculation includes CSS scroll-margin. | boolean | false |
ConfigProvider.form
| Property | Description | Type | Default |
|---|---|---|---|
validateMessages | General form templates, on top of the locale with nested groups combined; local Form.validateMessages takes precedence. | ValidateMessages | locale.Form.defaultValidateMessages |
colon | General horizontal label colon. | boolean | true |
labelAlign | Alignment of labels. | left | right | right |
labelWrap | Transfer of labels. | boolean | false |
requiredMark | Visual mandatory mark. | FormRequiredMark | true |
class | Native form class. | string | — |
style | CSS native form. | string | — |
classNames | Semantic slots classes. | FormSemantic | — |
styles | CSS lines semantic slots. | FormSemantic | — |
tooltip | Defaults prompt fields. | FormTooltipProps | — |
scrollToFirstError | General behavior after an unsuccessful submit. | boolean | FormScrollOptions | — |
Form supports nested NamePath, lists, metadata, selective reset, field defaults, and scrolling to errors. Connect the value with a control snippet or pass the value and change handler explicitly. Set validation dependencies with dependencies and choose the events with validateTrigger. Set the size with Form.size and the field variant with Form.variant. Use Form.Provider to coordinate forms.
Form.component=false provides context without a native form element. ref.submit() submits the mounted form programmatically. The example shares the outer form model, so its native actions cover both fields. The nearest Form without a variant clears the outer form variant. The component setting or ConfigProvider.variant then applies.
Semantic DOM
Form and ConfigProvider.form support object and functional classNames/styles. styles values are CSS strings; local style overrides semantic root. FormItem accepts class/rootClassName/style. Captions, tooltip, help and extra are isolated from field binding; The complex label is associated with the control via aria-labelledby.
| Element | Purpose |
|---|---|
root | Native form; missing when component=false. |
label | Field label, including requiredMark and tooltip. |
content | children area inside control. |
help | Block errors/warnings or help. |
helpItem | Separate message or rich help wrapper. |
extra | Permanent explanation next to messages. |
| Element | Purpose |
|---|---|
form.ant-form | By default, a real form with native submit/reset. component=false passes only the context, without the DOM and handlers. |
.ant-form-item | Field container, verification statuses and class. |
.ant-form-item-label | Label label, htmlFor and mandatory marker. |
.ant-form-item-control | Control and accessible description. |
.ant-form-item-explain | Field errors and warnings; FormItem links them via aria-describedby. The warning does not set aria-invalid. |
.ant-form-item-extra | help without errors/warnings and a separate permanent extra. |
[aria-invalid] | Invalid control. Scrolling and focus after a failed send is controlled by scrollToFirstError. |
FormList (no DOM) | The list itself does not create a wrapper. Fieldset, legend, row actions and message roles belong to the example. |
FormErrorList | Container ant-form-item-explain and separate error/warning messages. The ant-form-item class and the alert/status role are specified by the example wrapper. |
Registration tokens
Form tokens apply to captions and indentation, including inline layout. The example switches them without resetting the form model; the RTL direction is maintained. The current values of the common tokens are shown below.
| Token | Purpose |
|---|---|
labelRequiredMarkColor | Mandatory marker color. |
labelColor | Label color. |
labelFontSize | Label font size. |
labelHeight | Label height. |
verticalLabelHeight | Vertical label height. |
labelColonMarginInlineStart | Indent to colon. |
labelColonMarginInlineEnd | Indentation after colon. |
itemMarginBottom | Bottom padding of FormItem. |
inlineItemMarginBottom | Bottom margin of the field in inline layout. |
verticalLabelPadding | Padding vertical label. |
verticalLabelMargin | Margin of vertical label. |
| Token | Meaning |
|---|---|
colorText | rgba(0,0,0,0.88) |
colorError | #ff4d4f |
colorTextSecondary | rgba(0,0,0,0.65) |
fontSize | 14 |
lineHeight | 1.5714285714285714 |
marginLG | 24 |
paddingXS | 8 |
FAQ
Why doesn't FormItem pass value to the child control?
Use the control snippet on Form.Item to access the mapped field props. You can also pass value or checked and a change handler explicitly. The basic form shows the explicit connection.
Why doesn't defaultValue populate the model?
The model is created from initialValues. When a control receives an explicit value from the model, it determines the value shown. For initial data, use initialValues or default of a separate FormItem, for the server response after loading - setFieldsValue.
How to check password confirmation and other dependencies?
Compare values in validator(value, values). Set dependencies to the full paths the field depends on. Editing one of those controls can trigger validation again. Use $derived for computed text. The registration example shows revalidation of a related field.
Why doesn't the line with a dot access the nested field?
The string remains the literal key. Pass ['profile', 'name'] for the nested value rather than 'profile.name'. Inside the FormList, the FormItem is given a relative name; reading and writing through model methods requires the full path from the root of the form. Example paths shows this difference.
Why should line errors move with it?
Key each by field.key, not by index. The current field.name changes when move or the adjacent row is deleted, but the key and control instance are preserved. Dynamic list uses this rule for values and local errors.
What is more important: the initialValues of the form or the initialValue of the list?
The form value takes precedence even if it is an empty array. FormList.initialValue only fills the missing array. The initial values of the individual FormItems in the list are not set; use form, list or add(defaultValue).
Where to display FormList errors?
Snippet receives meta.errors and meta.warnings. Pass them to FormErrorList, as in example: the wrapper class ant-form-item preserves the styling, and role="alert" for errors and role="status" for warnings declare the messages. FormErrorList also accepts help, which replaces lists of messages. Nested field errors are read through getFieldError and getFieldsError; form.errors contains only the top level.
Why does required not require you to enable Checkbox?
The value false is valid for a boolean field and is not empty. For consent, add a validator that only accepts true. The visual mandatory marker does not perform the check itself.
How to check fields without sending data?
Call validateFields() and process the rejected Promise. By default the method shows errors. validateFields({ validateOnly: true }) checks without changing messages; the choice of paths and options can be combined. Test modes show the differences between validateOnly, recursive and dirty.
Why is dirty checking a field that I haven't edited yet?
An initial value other than undefined already includes the field in the dirty filter. Even an empty string is considered a given default. After reset, such fields continue to participate; The history of changes and routine checks is reset. This is separate from touched, which is counted through blur, touchField and submit.
Why does checking another field make the same outOfDate result?
The freshness of the Promise applies to the entire model, so a newer call to validation makes the previous result obsolete. Messages from different fields can be displayed independently. Do not use an outdated snapshot for submission or application result; this rule also applies to validateOnly.
Why did allTouched for the profile group become true after one field?
In isFieldsTouched(names, true), each names element defines a group. One touched child in each group is enough. For all individual fields, list their leaf paths, or call isFieldsTouched(true) without a list of names. Example states shows the difference.
Why is the parent path's validating false when its field is validated?
isFieldsValidating matches exact names. Pass the full path of the field or call the method without names for the entire model. This is different from prefix selection in touched queries. Silent checking does not include validating.
Where to show the server error?
For a specific field error, use setFields with full name and errors, as in batch update. For a field without rules, a manual error does not itself block submit; For repeated blocking check, a validator is needed. For onFinish execution error, use onError and application state. onFinishFailed is for rule errors. Asynchronous example saves the entered values for resending.
Why doesn't getFieldsValue return all initialValues?
Without arguments, the method reads the bindings, not all the store keys. UI fields are registered after mount; fields with model rules are available without UI. The entire store, including hidden values, returns getFieldsValue(true) without a filter. Reading example shows the difference and null for the metadata of an explicitly selected unregistered path.
Why does a filter that excludes all fields leave people: []?
The root of the FormList is filled separately from the filter. After excluding the string fields, an empty list array is left. Read the full row values, including data without controls, via getFieldsValue(true).
Does resetFields recreate all controls?
Without an argument, the contents of all registered FormItems and FormList strings are recreated. When selecting names, only the corresponding bindings are recreated. Adjacent fields are preserved and the state of the form's parent is reset separately. Selective example shows InputNumber and list; nested lists — restoration of initialValue.
Why did the profile reset keep the nested name error?
The parent's values are restored along with the children, but the metadata is retrieved from the exact path. To clear the error and touched name, call resetFields([['profile', 'name']]). In example you can compare both actions.
How to store date and convert input?
Dayjs is stored directly in the model. The format for the server API, UTC or ISO, is chosen by the application when submitting. Date in model saves the original object. Input normalization converts the value in the handler before setFieldValue; FormItem does not have the normalize property of the same name.
Is it possible to use a custom Svelte field component?
Yes, if it accepts a value and reports a change. Link it to the model explicitly, save the label, an accessible name, and the ability to focus an invalid control. Own control wraps InputNumber and uses the same update contract.
How to adjust the indentation and design of the form?
Use vertical/horizontal/inline, labelCol/wrapperCol and local layout Item. Form and ConfigProvider.form support semantic classNames/styles; FormItem - class/rootClassName/style. See semantic example and speakers.
How is hidden different from removing a field?
hidden preserves DOM, meaning and rules. With unmount, local rules are removed. noStyle manages the layout separately, preserving the binding.
Why didn't transform remove spaces from Input?
transform prepares a value only for its rule. To change the store, use setFieldValue in the input handler.
Why didn't explicit success remove aria-invalid?
validateStatus changes the visual status. This error needs to be fixed or the metadata of the model needs to be changed.
Why was hook status not updated after destructuring?
useFormItemStatus returns a getter object. Read its fields in markup or $derived rather than storing separate initial values.