Form

A form collects, validates and submits a set of values. A Form draws the <form> and owns the layout and the submit flow; a FormItem is one row with a label, the control, its messages and a hint. The control is connected through an explicit field object, so any control works with it and nothing leaks into popups. Rules are checked by @rc-component/async-validator, and a failed submit moves focus to the first invalid field.

Import
import { Form, FormItem, createForm } from 'svelte-ant-design';
Links
src/lib/Form Report an issue Component README

When to use

  • Use it to collect information and to validate fields against rules.
  • Use it for the layout of labels, controls, messages and hints, even when there are no rules.
  • For one field with no label and no rules, the bare control is simpler.

Typed values and your own model

Pass the shape of the values to createForm as a type argument: createForm<Signup>(). The instance, and the Form that gets it, are typed from it: onfinish receives a Signup, getFieldValue('age') is a number, and a value of the wrong type is a compile error. Without a type argument everything stays loose, as Record<string, unknown>. The names of the items are not typed.

<script lang="ts">
  import { Form, FormItem, Input, createForm } from 'svelte-ant-design';

  interface Signup {
    username: string;
    age: number;
  }

  // Give the shape of the values to createForm.
  const form = createForm<Signup>();
</script>

<Form {form} initialValues={{ username: '', age: 18 }} onfinish={(values) => save(values.username, values.age)}>
  <FormItem name="username" label="Username">
    {#snippet children(field)}
      <Input bind:value={field.value} {...field.attrs} />
    {/snippet}
  </FormItem>
</Form>

<!-- form.getFieldValue('age') is a number; form.setFieldValue('age', 'x') is a compile error. -->

Example: A typed form

As in Vue, you can keep the values in your own object: give Form a $state object as model and bind a control to it. The type of that object is the type of the values, so nothing else has to be declared. form and model can be used together: the instance then only carries the methods and the state of the fields.

<script lang="ts">
  import { Form, FormItem, Input, createForm } from 'svelte-ant-design';

  interface Signup {
    username: string;
  }

  // Your own state holds the values, as in Vue; its interface describes them.
  const values: Signup = $state({ username: '' });
  // Optional: the instance is then only for its methods (reset, validate, ...).
  const form = createForm<Signup>();
</script>

<Form {form} model={values} onfinish={(submitted) => save(submitted)}>
  <FormItem name="username" label="Username" rules={[{ required: true }]}>
    {#snippet children(field)}
      <Input bind:value={values.username} status={field.status} {...field.attrs} />
    {/snippet}
  </FormItem>
</Form>

Example: Your own model

A change made to the model from outside (a bound control, an assignment in code) counts as a change by the user: the field is touched and validated. The methods of the instance (setFieldValue, resetFields) do not count. Pass a $state object: a plain object is written to, but markup that reads it does not update.

Examples

Basic form

A form with required fields. FormItem hands a field to its snippet: bind field.value, pass field.status and spread field.attrs. A failed submit focuses the first invalid field. The shape of the values is given to createForm as a type: createForm<Login>().

Binding other controls

Bind the prop the control uses: bind:checked for a Switch or Checkbox, bind:value for a group or a Select. A function binding converts the value, here text to a number.

layout

Layout

layout is horizontal (label beside the control), vertical (label above it) or inline (items in a row). Below 576 px the horizontal layout stacks the label above the control.

labelAlign
labelWrap
colon

Label and control columns

labelCol and wrapperCol are the props of Col. labelAlign aligns the label text, labelWrap lets a long label wrap, colon draws or hides the colon.

requiredMark

Required mark

requiredMark shows the star (true), hides it, writes (optional) after the labels of the fields that are not required, or takes a snippet that draws the label itself. The mark follows the rules; required on an item overrides it.

Optional, but it must be a url.

Validation rules

Rules are checked by @rc-component/async-validator: required, type, min, max, len, pattern, enum, whitespace, transform and message. A field validates while the user changes it.

validateTrigger
validateDebounce 500

Validations run: 0

Validate trigger and debounce

validateTrigger is change (while the user edits), blur (when the control loses focus) or both. validateDebounce waits for a pause in typing before it starts.

validateFirst

Rule order and warnings

validateFirst stops at the first failing rule. A rule with warningOnly shows its message as a warning and does not stop the submit.

validateStatus of the last item
validateStatus: warning

Status icon

hasFeedback gives the control an icon through field.feedback: place it in the suffix of an Input. The async check shows the validating icon while it runs. validateStatus sets a status by hand.

We will never share it.
Use at least 8 characters.
htmlFor=: a click on the label does not toggle the switch.

Help, extra hint and tooltip

help replaces the generated messages (false hides them), extra is a hint below the control, tooltip adds a help icon after the label. Each takes text or a snippet.

hidden
show the company field
preserve
getFieldsValue(true)
{
  "name": "Ann",
  "secret": "kept even when hidden",
  "role": "Engineer",
  "company": "Acme"
}

Initial value, hidden and preserve

initialValue gives a field its value when the form has none. hidden hides an item but the field is still collected and validated. preserve decides whether a field that leaves keeps its value.

Dependencies

dependencies validates a field again when the user changes another one. The confirmation is checked when the first password changes, but only once the user has touched it.

Nothing validated yet.

onvalueschange (the user only), onfieldschange (calls)

none yet / 0

getFieldsValue(), getFieldsError(), isFieldsTouched()
{
  "values": {},
  "errors": [],
  "touched": false
}

The form instance

createForm() returns the instance. Set values, reset, validate, and read the values and the messages. Values set from code clear the messages and raise no change callback.

scrollToFirstError

Submit and the first error

onfinish and onfinishfailed report the result. By default a failed submit scrolls to the first invalid field and focuses it (scrollToFirstError); true only scrolls, false does nothing.

size
variant
disabled

Disabled, size and variant

disabled, size and variant of the form are handed to a control by hand through field.disabled, field.size and field.variant. The form never changes a control by itself.

Styled through classNames and styles.

Styling the parts

classNames and styles of the form reach the six parts of every item: root, label, content, help, helpItem and extra.

Messages and templates

validateMessages replaces the generated texts of the form, message of a rule replaces one. Templates use ${name}, ${min}, ${max}, ${len} and the variables of messageVariables.

getFieldsValue()
{}

Dynamic fields

A name can be a path: ['users', index, 'name']. With {#each} and setFieldValue a list of fields grows and shrinks. A field is validated only while it is on the page.

onvalueschange(changed, all), typed

nothing yet

form.getFieldValue('newsletter') is a boolean

false

A typed form

createForm<Signup>() gives the instance the shape of the values. onfinish, onvalueschange, getFieldValue and setFieldValue are typed, and a wrong type is an error. The names of the items are not typed: they come through a context.

values: your own $state object
{
  "username": "",
  "email": "",
  "subscribe": false
}

Your own model

Pass your own $state object as model and bind a control to values.username: a change from outside counts as a change by the user, so the field is touched and validated. rules on the form are added to the rules of the items. resetFields writes the model back as it was when the form mounted.

Form API

PropertyDescriptionTypeDefault
formThe store of the form, from createForm(). Left out: the form makes one, and bind:form returns it. The type of the values, Values, is taken from it.FormInstance<Values>—
modelYour own $state object that holds the values of the fields: bind a control to values.username or to field.value. A change made to it from outside (a bound control, an assignment in code) counts as a change by the user: the field is touched, onvalueschange runs and the field is validated. The methods of the instance (setFieldValue, resetFields) do not count. Left out: the store keeps the values itself. Pass a $state object, or markup that reads it will not update.Values—
rulesThe rules by field name: a list per name, or an object for the names below it ({ user: { name: [rule] } }). The rules of the item with that name come after them, and either gives the required mark.FormRules—
initialValuesThe values the fields start with and resetFields returns to. Not reactive: a later change of the prop is ignored (use setFieldsValue). A field that a control binds needs an initial value. With model it fills only the keys the model lacks.DeepPartial<Values>—
nameThe prefix of the ids of the controls (signup_username). Left out: a unique id is used, so two forms never share ids.string—
layoutHow an item lays out its label and control.'horizontal' | 'vertical' | 'inline''horizontal'
labelColThe label column, as the props of Col. An item's own value wins. Below 576 px the horizontal layout stacks the label above the control unless this has an xs value.ComponentProps<typeof Col>—
wrapperColThe control column, as the props of Col. Without a span it takes the room that is left.ComponentProps<typeof Col>—
labelAlignThe alignment of the label text. start and end follow the text direction.'start' | 'end''end'
labelWrapWhether a long label wraps instead of being cut.booleanfalse
colonWhether a colon follows the label. Only in the horizontal layout; the room after the label stays without it.booleantrue
requiredMarkThe required mark: shown, hidden, the optional mark, or a snippet that draws the label. A form-level setting only.boolean | 'optional' | Snippet<[{ label, required }]>true
validateTriggerThe events that validate a field: a change by the user, the control losing focus, or both. The default of the items.'change' | 'blur' | ('change' | 'blur')[]'change'
validateMessagesThe templates of the generated messages, laid over the English defaults key by key. See the rule table for the variables.FormValidateMessages—
preserveWhether a field keeps its value when its item is destroyed. The default of the items.booleantrue
disabledHanded to the controls by hand through field.disabled. The form itself disables nothing.boolean—
sizeHanded to the controls by hand through field.size.'small' | 'medium' | 'large'—
variantHanded to the controls by hand through field.variant.'outlined' | 'borderless' | 'filled' | 'underlined'—
tooltipThe default props of every label tooltip, and the icon.FormTooltipConfig—
scrollToFirstErrorAfter a failed submit: scroll the first invalid control into view and focus it. true only scrolls, an object also takes the native scroll options, false moves nothing.boolean | (ScrollIntoViewOptions & { focus?: boolean }){ focus: true }
feedbackIconsThe icons of the items with hasFeedback, one snippet per status.Partial<Record<FormValidateStatus, Snippet>>—
classNamesExtra classes for the six parts of every item.Partial<Record<root | label | content | help | helpItem | extra, string>>—
stylesInline styles for the six parts of every item.Partial<Record<root | label | content | help | helpItem | extra, Record<string, string | number>>>—
onfinishCalled after a submit whose validation passed, with the values of the fields. Only the fields that have an item are in it: a field that can be hidden (for example by {#if}) is missing, so declare it optional in Values (age?: number).(values: Values) => void—
onfinishfailedCalled after a submit that failed validation, with { values, errorFields, outOfDate }.(info: FormFinishFailedInfo) => void—
onvalueschangeCalled after a change made by the user, with the changed value and all the values. Not called for values set from code.(changed: DeepPartial<Values>, all: Values) => void—
onfieldschangeCalled when any state of a field changes: value, touched, validating, errors or warnings. A validation reports validating true, then false with the result.(changed: FormFieldData[], all: FormFieldData[]) => void—
childrenThe items of the form.Snippet—
classAn additional CSS class.string—
styleInline style of the <form>.string—
native attributesNative <form> attributes except onsubmit (use onfinish). novalidate is set, because the rules validate; pass novalidate={false} to get the native validation back.HTMLFormAttributes—
Differences from Ant Design: a control is connected through an explicit field object (bind:value={field.value}), not by cloning the child, so valuePropName, trigger, getValueFromEvent, getValueProps, normalize, shouldUpdate and useWatch are not needed (a function binding converts a value; reading values is reactive), and the status of an item cannot leak into a popup of a control. A field that a control binds needs an initial value. scrollToFirstError is on by default. disabled, size, variant and the status reach controls through field, not a context (the context is planned). labelAlign takes start and end, validateTrigger takes change and blur, and the message of a rule is a string. The rules are checked by @rc-component/async-validator, the first dependency of the package. Form.List, Form.ErrorList, Form.Provider and noStyle are planned. The values can be typed (createForm<Values>()) and can live in your own $state object (model, as in Vue); the rules can also be given to the form by field name.

FormItem API

PropertyDescriptionTypeDefault
nameConnects the item to a field: a key, or a path (['user', 'city'], ['users', 0, 'name']). A number step makes an array. Left out: a row that only lays out its content.string | number | (string | number)[]—
labelThe label: text or a snippet. null keeps the label column and the colon with no text; left out there is no label column.string | Snippet | null—
rulesThe rules of the field. A rule can be a function of the form that returns one, to compare with another field.FormRule[]—
requiredThe mark and aria-required. Left out: derived from a required rule; false turns the mark off.boolean—
helpReplaces the generated messages. Text or a snippet; false shows no message.string | Snippet | false—
extraA hint below the control and the messages. Text or a snippet.string | Snippet—
tooltipA help icon after the label that opens a Tooltip: text, a snippet, or the props of Tooltip with icon and iconLabel (the accessible name of the icon, default More information).string | Snippet | FormTooltipConfig—
hasFeedbackGives the control a status icon through field.feedback. The object form replaces the icons of this item. Nothing is drawn unless you place field.feedback.boolean | { icons: Partial<Record<FormValidateStatus, Snippet>> }false
validateStatusSets the status by hand; it wins over the validation. Left out: derived (validating, error, warning, and success with hasFeedback).'success' | 'warning' | 'error' | 'validating'—
validateFirsttrue stops at the first failing rule. 'parallel' runs all the rules at once and keeps the messages of the first failing one.boolean | 'parallel'false
validateTriggerThe events that validate this field. A rule's own validateTrigger must be a subset of it.'change' | 'blur' | ('change' | 'blur')[]the form's
validateDebounceMilliseconds to wait before a validation starts; a newer change replaces a waiting one.number—
dependenciesFields whose change by the user validates this one again, if it has been touched or validated. A value set from code does not.(string | number | (string | number)[])[]—
initialValueThe value when the form has none; the initialValues of the form win.unknown—
hiddenHides the item (display: none); the field is still collected and validated.booleanfalse
preservefalse removes the value when the item is destroyed.booleanthe form's
messageVariablesExtra variables for the message templates.Record<string, string>—
colon / labelAlign / labelWrap / labelCol / wrapperColThe same as on the form; the item's value wins.as on the formthe form's
layoutThe layout of this item. A form of inline layout is a layout of the whole form, so it is not an option here.'horizontal' | 'vertical'the form's
htmlForThe for of the label. null removes it, so a click on the label does not reach the control (the control keeps its name).string | nullthe id of the control
childrenThe control. It receives the field object. An item with no name may hold any content.Snippet<[FormField]>—
class / styleAppended to the root.string—
native attributesNative <div> attributes go to the root.HTMLAttributes<HTMLDivElement>—

field: what an item hands to its control

PropertyDescriptionType
valueThe value of the field. The setter is the path of a change made by the user: it stores the value, marks the field touched, validates, and calls onvalueschange and the dependents. Bind it: bind:value={field.value}.any
statuserror or warning for the status prop of a control that has one (Input, Select); otherwise undefined.'error' | 'warning' | undefined
attrsid, aria-describedby (the messages and the extra hint, when they exist), aria-invalid (an error), aria-required and aria-labelledby (the label). Spread it on the control: {...field.attrs}.Record<string, string>
errors / warningsThe messages of the field.string[]
validating / touchedA validation is running; the user changed the field, or it was validated on blur.boolean
disabled / size / variantThe values of the form, for the matching props of the control. undefined leaves the control's own default.boolean | FormSize | FormVariant | undefined
feedbackThe hasFeedback icon as a snippet, for a suffix of the control; undefined when there is none to show.Snippet | undefined

FormInstance methods

MethodDescriptionType
getFieldValue(name)The value of a field. It is the live value: copy it before changing it. Reading it in markup, $derived or $effect is tracked.(name) => unknown
getFieldsValue(names?, { filter }?)The values as a nested object: the fields that have an item; true for every value in the store; a list of names for those; filter receives { touched, validating }. Typed: true gives the whole Values, the others a deep partial, so check a field before you use it.(names: true) => Values; (names?: name[], options?) => DeepPartial<Values>
setFieldValue(name, value)Sets a value and clears the messages of the field. It is not a user change: no callback, no validation, no dependencies.(name, value) => void
setFieldsValue(values)Merges values into the store, deeply, and clears the messages of the fields they reach. Arrays are replaced.(values) => void
getFieldError(name) / getFieldWarning(name)The error or warning messages of one field.(name) => string[]
getFieldsError(names?)Every field (or the listed ones) as { name, errors, warnings }.(names?) => FormFieldError[]
isFieldTouched(name) / isFieldsTouched(names?, allTouched?) / isFieldValidating(name)The flags of fields. isFieldsTouched is true when any (with allTouched, every) listed field was touched.(…) => boolean
setFields(fields)Sets any of the value, touched, validating, errors and warnings of fields. errors: [] clears the messages.(fields: FormFieldData[]) => void
validateFields(names?, config?)Validates the fields that have an item (or the listed ones) and resolves with their values (only the fields that have an item, as in onfinish); a failure rejects with { values, errorFields, outOfDate }. Fields with only warnings do not fail. config: validateOnly (show nothing), recursive (the fields below a path), dirty (only the touched or validated).(names?, config?) => Promise<values>
resetFields(names?)Back to the initial values (all fields, or the listed ones), with no touched flags and no messages.(names?) => void
submit()Does what a submit button does: validate, then onfinish or onfinishfailed. Needs a mounted Form.() => void
scrollToField(name, options?)Scrolls the control of a field into view (the native options), and focuses it with { focus: true }.(name, options?) => void

Rule keys

PropertyDescriptionType
requiredThe value must exist: undefined, null, an empty string and an empty array fail; 0, false and whitespace pass (add whitespace).boolean
typeThe type of the value, string unless set: string, number, boolean, integer, float, array, object, enum, url, email, tel, date, regexp, hex, method, any.FormRuleType
len / min / maxThe length of a string or array, the value of a number. len wins over a range.number
patternThe value must match.RegExp
enumWith type: 'enum': the allowed values.unknown[]
whitespaceWith type: 'string': a value of only whitespace fails.boolean
transformChanges the value before it is checked.(value) => any
messageThe text of the error: a string, used as a template. ${name} is the label (or the field name), the others are the values of the rule; \${ is kept as text. Left out: the generated message.string
validatorA check of your own: return nothing (it passed), or throw, reject, or return false, an error or errors to fail. It runs next to the other keys of the rule.(rule, value) => void | Promise<void>
warningOnlyA failure is shown as a warning and does not stop the submit.boolean
defaultField / fieldsWith type: 'array' or 'object': the rule of every element, or the rules of the keys.FormRuleConfig | Record<string, FormRuleConfig>
validateTriggerThe events that run this rule: a subset of the trigger of the item.'change' | 'blur' | ('change' | 'blur')[]

createForm and getFormInstance

MethodDescriptionType
createForm()Makes the store of a form: its values and the state of its fields. Pass it to <Form {form}> and call its methods from anywhere. Give it the shape of the values, createForm<Signup>(), and getFieldValue, setFieldValue, setFieldsValue, validateFields and the callbacks of the form are typed. It takes no argument: the initial values are a prop of the form.<Values extends object>() => FormInstance<Values>
getFormInstance()The instance of the nearest Form, for a component inside it (a custom control, a reset button). Call it while the component initializes; outside a Form it throws.<Values extends object>() => FormInstance<Values>

Design tokens

TokenDescriptionDefault
--ads-form-item-margin-bottomThe space after an item. A message of one line fits into it, so showing it moves nothing.24px
--ads-form-label-colorColour of the label.var(--ads-color-text)
--ads-form-label-font-sizeFont size of the label and the star.var(--ads-font-size)
--ads-form-required-mark-colorColour of the star.var(--ads-color-danger-text)
--ads-form-help-colorColour of a neutral message. tokens-accessible.css darkens it to #666666.var(--ads-color-text-tertiary)
--ads-form-extra-colorColour of the extra hint and of (optional). tokens-accessible.css darkens it to #666666.var(--ads-color-text-tertiary)
--ads-form-error-textColour of an error message.var(--ads-color-danger-text)
--ads-form-warning-textColour of a warning message. tokens-accessible.css darkens it to #874d00.#faad14
--ads-form-success-iconColour of the success icon. tokens-accessible.css darkens it to #389e0d.#52c41a
--ads-form-warning-iconColour of the warning icon. tokens-accessible.css darkens it to #ad6800.#faad14
--ads-form-error-iconColour of the error icon.#ff4d4f
--ads-form-tooltip-icon-colorColour of the help icon of a label. tokens-accessible.css darkens it to #737373.var(--ads-color-text-tertiary)

Accessibility

  • The label is a native <label for>. The star and the colon are aria-hidden elements, not generated content, so the name of the control is the label text alone. The control also gets aria-labelledby (the label), so it keeps its name when htmlFor={null} stops a click on the label from reaching it.
  • field.attrs points aria-describedby at the messages and the extra hint, and only at ids that exist; aria-invalid is set for an error only (a warning is described, not invalid); aria-required follows the rules.
  • The messages are neither a live region nor role="alert": a screen reader reads them through aria-describedby when the control gets focus. What announces a failed submit is the move of focus to the first invalid field (scrollToFirstError, on by default). If you turn it off, tell the user yourself that the submit failed.
  • The help icon of a label is a button after the label: it takes Tab, opens its tooltip on focus and hover, and Escape closes it. Give it a name in your language with iconLabel.
  • A validation that runs on every change waits for the end of an IME composition, so no message appears under a half-typed syllable; it runs when the composition ends.
  • A status is never colour alone: the star and the messages are text and the status icons differ in shape. In forced-colors mode the system colours replace the rest. Use tokens-accessible.css for messages and icons that reach WCAG AA.
  • Not checked yet: NVDA, JAWS and VoiceOver, a real IME keyboard on a phone, and real touch devices other than the Chromium emulation. Orca with Firefox is checked by an automated test.