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.
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
setFieldValue, resetFields) do not count. Pass a $state object: a plain object is written to, but markup that reads it does not update.Examples
<script lang="ts">
import { Button, Checkbox, Form, FormItem, Input, createForm } from 'svelte-ant-design';
// The shape of the values is the type argument of createForm. It is optional: createForm() alone is loose.
interface Login {
username: string;
password: string;
remember: boolean;
}
const form = createForm<Login>();
// Another way, as in Vue: keep the values in your own $state object and pass it as `model`:
// const values: Login = $state({ username: '', password: '', remember: true });
// <Form {form} model={values}> ... <Input bind:value={values.username} /> ...
// See the example "Your own model" below.
let result = $state('');
</script>
<div class="stage">
<div class="sheet">
<Form
{form}
name="basic"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
initialValues={{ username: '', password: '', remember: true }}
onfinish={(values) => (result = `Success: ${JSON.stringify(values)}`)}
onfinishfailed={() => (result = 'Failed: the form has errors.')}
>
<FormItem name="username" label="Username" rules={[{ required: true, message: 'Please input your username!' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="password" label="Password" rules={[{ required: true, message: 'Please input your password!' }]}>
{#snippet children(field)}
<Input type="password" bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="remember" wrapperCol={{ offset: 8, span: 16 }}>
{#snippet children(field)}
<Checkbox bind:checked={field.value} {...field.attrs}>Remember me</Checkbox>
{/snippet}
</FormItem>
<FormItem wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
{#if result}
<div class="results">
<p role="status">{result}</p>
</div>
{/if}
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
</style>
<script lang="ts">
import { Button, Checkbox, CheckboxGroup, Form, FormItem, Input, RadioGroup, Select, Switch, createForm } from 'svelte-ant-design';
const form = createForm();
let result = $state('');
</script>
<div class="stage">
<div class="sheet">
<Form
{form}
name="binding"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
initialValues={{ alerts: false, agree: false, hobbies: ['music'], plan: 'free', city: 'oslo', amount: 10 }}
onfinish={(values) => (result = JSON.stringify(values))}
onfinishfailed={() => (result = 'Failed: the form has errors.')}
>
<FormItem name="alerts" label="Switch">
{#snippet children(field)}
<Switch bind:checked={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="agree" label="Checkbox" rules={[{ type: 'enum', enum: [true], message: 'You must agree' }]}>
{#snippet children(field)}
<Checkbox bind:checked={field.value} {...field.attrs}>I agree</Checkbox>
{/snippet}
</FormItem>
<FormItem name="hobbies" label="CheckboxGroup">
{#snippet children(field)}
<CheckboxGroup
bind:value={field.value}
options={[
{ value: 'music', label: 'Music' },
{ value: 'film', label: 'Film' },
{ value: 'sport', label: 'Sport' }
]}
{...field.attrs}
/>
{/snippet}
</FormItem>
<FormItem name="plan" label="RadioGroup">
{#snippet children(field)}
<RadioGroup
bind:value={field.value}
options={[
{ value: 'free', label: 'Free' },
{ value: 'pro', label: 'Pro' }
]}
{...field.attrs}
/>
{/snippet}
</FormItem>
<FormItem name="city" label="Select">
{#snippet children(field)}
<Select
bind:value={field.value}
status={field.status}
options={[
{ value: 'oslo', label: 'Oslo' },
{ value: 'riga', label: 'Riga' }
]}
{...field.attrs}
/>
{/snippet}
</FormItem>
<FormItem name="amount" label="Function binding" rules={[{ type: 'number', min: 1, message: 'A number from 1' }]}>
{#snippet children(field)}
<Input
bind:value={() => String(field.value ?? ''), (text) => (field.value = text === '' ? undefined : Number(text))}
status={field.status}
{...field.attrs}
/>
{/snippet}
</FormItem>
<FormItem wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
{#if result}
<div class="results">
<p role="status">{result}</p>
</div>
{/if}
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
</style>
<script lang="ts">
import { Button, Form, FormItem, Input, RadioGroup, createForm } from 'svelte-ant-design';
const form = createForm();
let layout = $state<'horizontal' | 'vertical' | 'inline'>('horizontal');
</script>
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">layout</span>
<RadioGroup
bind:value={layout}
optionType="button"
options={[
{ value: 'horizontal', label: 'horizontal' },
{ value: 'vertical', label: 'vertical' },
{ value: 'inline', label: 'inline' }
]}
/>
</div>
</div>
<div class="sheet">
<Form
{form}
name="layout"
{layout}
labelCol={layout === 'horizontal' ? { span: 4 } : undefined}
wrapperCol={layout === 'horizontal' ? { span: 14 } : undefined}
initialValues={{ first: '', second: '' }}
>
<FormItem name="first" label="Field A">
{#snippet children(field)}
<Input bind:value={field.value} placeholder="input placeholder" {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="second" label="Field B">
{#snippet children(field)}
<Input bind:value={field.value} placeholder="input placeholder" {...field.attrs} />
{/snippet}
</FormItem>
<FormItem wrapperCol={layout === 'horizontal' ? { offset: 4, span: 14 } : undefined}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
</style>
<script lang="ts">
import { Form, FormItem, Input, RadioGroup, Switch, createForm } from 'svelte-ant-design';
const form = createForm();
let labelAlign = $state<'start' | 'end'>('end');
let labelWrap = $state(false);
let colon = $state(true);
</script>
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">labelAlign</span>
<RadioGroup
bind:value={labelAlign}
optionType="button"
options={[
{ value: 'start', label: 'start' },
{ value: 'end', label: 'end' }
]}
/>
</div>
<div class="field">
<span class="caption">labelWrap</span>
<Switch bind:checked={labelWrap} aria-label="labelWrap" />
</div>
<div class="field">
<span class="caption">colon</span>
<Switch bind:checked={colon} aria-label="colon" />
</div>
</div>
<div class="sheet">
<Form
{form}
name="label-col"
labelCol={{ span: 6 }}
wrapperCol={{ span: 18 }}
{labelAlign}
{labelWrap}
{colon}
initialValues={{ short: '', long: '' }}
>
<FormItem name="short" label="Short">
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="long" label="A long label that does not fit in its column">
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
</style>
<script lang="ts">
import { Form, FormItem, Input, RadioGroup, createForm } from 'svelte-ant-design';
const form = createForm();
type Mark = 'shown' | 'hidden' | 'optional' | 'snippet';
let mark = $state<Mark>('shown');
</script>
{#snippet custom({ label, required }: { label: unknown; required: boolean })}
<span>{label} {required ? '(must)' : '(may)'}</span>
{/snippet}
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">requiredMark</span>
<RadioGroup
bind:value={mark}
optionType="button"
options={[
{ value: 'shown', label: 'true' },
{ value: 'hidden', label: 'false' },
{ value: 'optional', label: "'optional'" },
{ value: 'snippet', label: 'snippet' }
]}
/>
</div>
</div>
<div class="sheet">
<Form
{form}
name="required-mark"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
requiredMark={mark === 'shown' ? true : mark === 'hidden' ? false : mark === 'optional' ? 'optional' : custom}
initialValues={{ name: '', nickname: '', email: '' }}
>
<FormItem name="name" label="Name" rules={[{ required: true }]}>
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="nickname" label="Nickname">
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="email" label="Email (required={false})" required={false} rules={[{ required: true }]}>
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
</style>
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from 'svelte-ant-design';
const form = createForm();
let result = $state('');
</script>
<div class="stage">
<div class="sheet">
<Form
{form}
name="rules"
labelCol={{ span: 7 }}
wrapperCol={{ span: 17 }}
initialValues={{ username: '', email: '', age: '', website: '', code: '' }}
onfinish={(values) => (result = `Success: ${JSON.stringify(values)}`)}
onfinishfailed={() => (result = 'Failed: the form has errors.')}
>
<FormItem
name="username"
label="Username"
rules={[
{ required: true, whitespace: true, message: 'Please input a username' },
{ min: 3, max: 12, message: '${name} must be 3 to 12 characters' },
{ pattern: /^[a-z0-9_]+$/, message: 'Use lowercase letters, digits and _' }
]}
>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="email" label="Email" rules={[{ required: true }, { type: 'email' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem
name="age"
label="Age"
rules={[{ type: 'number', min: 18, max: 99, transform: (value) => (value === '' ? undefined : Number(value)), message: '${name} must be a number from ${min} to ${max}' }]}
>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="website" label="Website" rules={[{ type: 'url' }]} extra="Optional, but it must be a url.">
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="code" label="Code" rules={[{ len: 6, message: 'The code has exactly ${len} characters' }, { pattern: /^\d+$/, message: 'Digits only' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem wrapperCol={{ offset: 7, span: 17 }}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
{#if result}
<div class="results">
<p role="status">{result}</p>
</div>
{/if}
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
</style>
Validations run: 0
<script lang="ts">
import { Form, FormItem, Input, RadioGroup, Switch, createForm } from 'svelte-ant-design';
const form = createForm();
type Trigger = 'change' | 'blur' | 'both';
let trigger = $state<Trigger>('change');
let debounce = $state(false);
let runs = $state(0);
</script>
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">validateTrigger</span>
<RadioGroup
bind:value={trigger}
optionType="button"
options={[
{ value: 'change', label: 'change' },
{ value: 'blur', label: 'blur' },
{ value: 'both', label: 'both' }
]}
/>
</div>
<div class="field">
<span class="caption">validateDebounce 500</span>
<Switch bind:checked={debounce} aria-label="validateDebounce" />
</div>
</div>
<div class="sheet">
<Form
{form}
name="trigger"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
validateTrigger={trigger === 'both' ? ['change', 'blur'] : trigger}
initialValues={{ nick: '' }}
>
<FormItem
name="nick"
label="Nickname"
validateDebounce={debounce ? 500 : undefined}
rules={[
{ min: 3, message: 'At least 3 characters' },
{
validator: () => {
runs += 1;
}
}
]}
>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</div>
<div class="results">
<p role="status">Validations run: {runs}</p>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
</style>
<script lang="ts">
import { Form, FormItem, Input, Switch, createForm } from 'svelte-ant-design';
const form = createForm();
let first = $state(false);
</script>
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">validateFirst</span>
<Switch bind:checked={first} aria-label="validateFirst" />
</div>
</div>
<div class="sheet">
<Form {form} name="first" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} initialValues={{ password: '' }}>
<FormItem
name="password"
label="Password"
validateFirst={first}
rules={[
{ required: true, message: 'Please input a password' },
{ min: 8, message: 'At least 8 characters' },
{ pattern: /\d/, message: 'Add a digit' },
{ pattern: /^(?!password)/i, message: 'That password is very common', warningOnly: true }
]}
>
{#snippet children(field)}
<Input type="text" bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
</style>
<script lang="ts">
import { Form, FormItem, Input, RadioGroup, createForm } from 'svelte-ant-design';
const form = createForm();
type Status = 'success' | 'warning' | 'error' | 'validating';
let status = $state<Status>('warning');
// A check that takes a second, to show the validating icon.
const free = (name: string) =>
new Promise<void>((resolve, reject) => setTimeout(() => (name === 'admin' ? reject('That name is taken') : resolve()), 1000));
</script>
{#snippet tick()}
<span aria-hidden="true">✔</span>
{/snippet}
{#snippet wait()}
<span aria-hidden="true">…</span>
{/snippet}
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">validateStatus of the last item</span>
<RadioGroup
bind:value={status}
optionType="button"
options={[
{ value: 'success', label: 'success' },
{ value: 'warning', label: 'warning' },
{ value: 'error', label: 'error' },
{ value: 'validating', label: 'validating' }
]}
/>
</div>
</div>
<div class="sheet">
<Form
{form}
name="feedback"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
feedbackIcons={{ validating: wait }}
initialValues={{ name: '', mail: 'me@example.com', manual: 'value' }}
>
<FormItem
name="name"
label="Name (try admin)"
hasFeedback
rules={[{ required: true, message: 'Please input a name' }, { validator: (_rule, value) => (value ? free(value) : undefined) }]}
>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs}>
{#snippet suffix()}{@render field.feedback?.()}{/snippet}
</Input>
{/snippet}
</FormItem>
<FormItem name="mail" label="Email" hasFeedback={{ icons: { success: tick } }} rules={[{ type: 'email', message: 'Not an email' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs}>
{#snippet suffix()}{@render field.feedback?.()}{/snippet}
</Input>
{/snippet}
</FormItem>
<FormItem name="manual" label="Status by hand" hasFeedback validateStatus={status} help="validateStatus: {status}">
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs}>
{#snippet suffix()}{@render field.feedback?.()}{/snippet}
</Input>
{/snippet}
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
</style>
<script lang="ts">
import { Form, FormItem, Input, Switch, createForm } from 'svelte-ant-design';
const form = createForm();
</script>
{#snippet richHelp()}
Use at least <b>8</b> characters.
{/snippet}
<div class="stage">
<div class="sheet">
<Form
{form}
name="help"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
initialValues={{ one: '', two: '', three: '', four: '', five: false }}
>
<FormItem name="one" label="With a tooltip" tooltip="Shown on hover and on keyboard focus.">
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="two" label="Tooltip props" tooltip={{ title: 'Placed below', placement: 'bottom', icon: 'i', iconLabel: 'About this field' }}>
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="three" label="Extra hint" extra="We will never share it.">
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="four" label="Own help" help={richHelp} rules={[{ min: 8 }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="five" label="Label click off" htmlFor={null} extra="htmlFor={null}: a click on the label does not toggle the switch.">
{#snippet children(field)}
<Switch bind:checked={field.value} {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
</style>
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from 'svelte-ant-design';
const form = createForm();
</script>
<div class="stage">
<div class="sheet">
<Form {form} name="register" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} initialValues={{ password: '', confirm: '' }}>
<FormItem name="password" label="Password" rules={[{ required: true, message: 'Please input your password!' }]}>
{#snippet children(field)}
<Input type="password" bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem
name="confirm"
label="Confirm"
dependencies={['password']}
rules={[
{ required: true, message: 'Please confirm your password!' },
(form) => ({
validator(_rule, value) {
if (!value || form.getFieldValue('password') === value) return;
return Promise.reject('The two passwords do not match!');
}
})
]}
>
{#snippet children(field)}
<Input type="password" bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">Register</Button>
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
</style>
Nothing validated yet.
none yet / 0
{
"values": {},
"errors": [],
"touched": false
}<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from 'svelte-ant-design';
const form = createForm();
let outcome = $state('Nothing validated yet.');
let change = $state('none yet');
let events = $state(0);
async function check() {
try {
await form.validateFields();
outcome = 'validateFields resolved';
} catch (info) {
outcome = `validateFields rejected: ${(info as { errorFields: { name: string[] }[] }).errorFields.map((field) => field.name.join('.')).join(', ')}`;
}
}
</script>
<div class="stage">
<div class="sheet">
<Form {form} name="instance" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} initialValues={{ name: '', note: 'start' }}
onvalueschange={(changed) => (change = JSON.stringify(changed))}
onfieldschange={() => (events += 1)}
>
<FormItem name="name" label="Name" rules={[{ required: true, message: 'Please input a name' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="note" label="Note">
{#snippet children(field)}
<Input bind:value={field.value} {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</div>
<div class="row">
<Button onclick={() => form.setFieldsValue({ name: 'Ann', note: 'filled from code' })}>Fill</Button>
<Button onclick={() => form.resetFields()}>Reset</Button>
<Button onclick={check}>Validate</Button>
<Button onclick={() => form.setFields([{ name: ['name'], errors: [] }])}>Clear messages</Button>
</div>
<div class="results">
<p role="status">{outcome}</p>
<div class="field">
<span class="caption">onvalueschange (the user only), onfieldschange (calls)</span>
<p>{change} / {events}</p>
</div>
<div class="field">
<span class="caption">getFieldsValue(), getFieldsError(), isFieldsTouched()</span>
<pre>{JSON.stringify({ values: form.getFieldsValue(), errors: form.getFieldsError().map((field) => field.errors), touched: form.isFieldsTouched() }, null, 2)}</pre>
</div>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
.results pre {
box-sizing: border-box;
margin: 0;
max-width: 100%;
overflow-x: auto;
padding: 10px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 10px;
background: var(--ads-color-bg-container);
font-size: 12px;
}
</style>
<script lang="ts">
import { Button, Form, FormItem, Input, RadioGroup, createForm } from 'svelte-ant-design';
const form = createForm();
type Mode = 'focus' | 'scroll' | 'off';
let mode = $state<Mode>('focus');
let active = $state('');
const rows = [1, 2, 3, 4, 5, 6];
function where() {
// The first invalid field has been scrolled to, and focused with the default.
setTimeout(() => {
const element = document.activeElement;
active = element && element.id ? `Focus is on: ${element.id}` : 'Focus did not move.';
}, 50);
}
</script>
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">scrollToFirstError</span>
<RadioGroup
bind:value={mode}
optionType="button"
options={[
{ value: 'focus', label: '{ focus: true } (default)' },
{ value: 'scroll', label: 'true' },
{ value: 'off', label: 'false' }
]}
/>
</div>
</div>
<div class="sheet">
<Form
{form}
name="submit"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
scrollToFirstError={mode === 'focus' ? { focus: true } : mode === 'scroll' ? true : false}
initialValues={Object.fromEntries(rows.map((row) => [`field${row}`, row === 3 || row === 5 ? '' : 'ok']))}
onfinishfailed={where}
>
{#each rows as row (row)}
<FormItem name="field{row}" label="Field {row}" rules={row === 3 || row === 5 ? [{ required: true, message: 'Field {row} is required' }] : []}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
{/each}
<FormItem wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
{#if active}
<div class="results">
<p role="status">{active}</p>
</div>
{/if}
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
</style>
<script lang="ts">
import { Form, FormItem, Input, RadioGroup, Select, Switch, createForm } from 'svelte-ant-design';
const form = createForm();
type Size = 'small' | 'medium' | 'large';
type Variant = 'outlined' | 'borderless' | 'filled' | 'underlined';
let size = $state<Size>('medium');
let variant = $state<Variant>('outlined');
let disabled = $state(false);
</script>
<div class="stage">
<div class="controls">
<div class="field">
<span class="caption">size</span>
<RadioGroup
bind:value={size}
optionType="button"
options={[
{ value: 'small', label: 'small' },
{ value: 'medium', label: 'medium' },
{ value: 'large', label: 'large' }
]}
/>
</div>
<div class="field">
<span class="caption">variant</span>
<RadioGroup
bind:value={variant}
optionType="button"
options={[
{ value: 'outlined', label: 'outlined' },
{ value: 'filled', label: 'filled' },
{ value: 'borderless', label: 'borderless' },
{ value: 'underlined', label: 'underlined' }
]}
/>
</div>
<div class="field">
<span class="caption">disabled</span>
<Switch bind:checked={disabled} aria-label="disabled" />
</div>
</div>
<div class="sheet">
<Form {form} name="pass" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} {size} {variant} {disabled} initialValues={{ name: '', city: 'oslo' }}>
<FormItem name="name" label="Name">
{#snippet children(field)}
<Input bind:value={field.value} disabled={field.disabled} size={field.size} variant={field.variant} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="city" label="City">
{#snippet children(field)}
<Select
bind:value={field.value}
disabled={field.disabled}
size={field.size}
variant={field.variant}
options={[
{ value: 'oslo', label: 'Oslo' },
{ value: 'riga', label: 'Riga' }
]}
{...field.attrs}
/>
{/snippet}
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 12px 24px;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
</style>
<script lang="ts">
import { Form, FormItem, Input, createForm } from 'svelte-ant-design';
const form = createForm();
</script>
<div class="stage">
<div class="sheet">
<Form
{form}
name="semantic"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
classNames={{ root: 'demo-item', helpItem: 'demo-help-item' }}
styles={{ label: { 'font-weight': 600 }, extra: { 'font-style': 'italic' }, content: { 'border-inline-start': '3px solid var(--ads-color-primary)', 'padding-inline-start': '8px' } }}
initialValues={{ name: '' }}
>
<FormItem name="name" label="Name" extra="Styled through classNames and styles." rules={[{ required: true, message: 'Please input a name' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.stage :global(.demo-help-item) {
text-decoration: underline dotted;
}
</style>
<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from 'svelte-ant-design';
const form = createForm();
</script>
<div class="stage">
<div class="sheet">
<Form
{form}
name="messages"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
validateMessages={{ required: 'Please fill in ${name}.', string: { min: '${name} needs at least ${min} characters.' } }}
initialValues={{ name: '', handle: '', city: '' }}
>
<FormItem name="name" label="Full name" rules={[{ required: true }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="handle" label="Handle" rules={[{ min: 4 }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem
name="city"
label="City"
messageVariables={{ where: 'the city you live in' }}
rules={[{ required: true, message: 'Tell us ${where}, ${name} is empty.' }]}
>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
</style>
{}<script lang="ts">
import { Button, Form, FormItem, Input, createForm } from 'svelte-ant-design';
const form = createForm();
let count = $state(2);
function add() {
form.setFieldValue(['users', count, 'name'], '');
count += 1;
}
function removeLast() {
count -= 1;
}
</script>
<div class="stage">
<div class="sheet">
<Form {form} name="dynamic" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} initialValues={{ users: [{ name: 'Ann' }, { name: '' }] }}>
{#each Array.from({ length: count }, (_, index) => index) as index (index)}
<FormItem name={['users', index, 'name']} label="Name {index + 1}" preserve={false} rules={[{ required: true, message: 'Please input a name' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
{/each}
</Form>
</div>
<div class="row">
<Button onclick={add}>Add a field</Button>
<Button onclick={removeLast} disabled={count <= 1}>Remove the last</Button>
</div>
<div class="results">
<div class="field">
<span class="caption">getFieldsValue()</span>
<pre>{JSON.stringify(form.getFieldsValue(), null, 2)}</pre>
</div>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results pre {
box-sizing: border-box;
margin: 0;
max-width: 100%;
overflow-x: auto;
padding: 10px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 10px;
background: var(--ads-color-bg-container);
font-size: 12px;
}
</style>
nothing yet
false
<script lang="ts">
import { Button, Form, FormItem, Input, Switch, createForm } from 'svelte-ant-design';
interface Signup {
username: string;
newsletter: boolean;
}
// The shape of the values is given once: the instance and the callbacks of the form follow it.
const form = createForm<Signup>();
let result = $state('');
let latest = $state('nothing yet');
</script>
<div class="stage">
<div class="sheet">
<Form
{form}
name="typed"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
initialValues={{ username: '', newsletter: false }}
onfinish={(values) => (result = `Welcome, ${values.username.toUpperCase()}`)}
onvalueschange={(changed, all) => (latest = `${Object.keys(changed).join(', ')} changed; newsletter is ${all.newsletter}`)}
>
<FormItem name="username" label="Username" rules={[{ required: true, message: 'Please input a username' }]}>
{#snippet children(field)}
<Input bind:value={field.value} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="newsletter" label="Newsletter">
{#snippet children(field)}
<Switch bind:checked={field.value} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
<div class="row">
<Button onclick={() => form.setFieldValue('newsletter', true)}>Subscribe from code</Button>
<Button onclick={() => form.setFieldsValue({ username: 'ann' })}>Fill the name</Button>
</div>
<div class="results">
{#if result}
<div class="field">
<span class="caption">onfinish, typed: values.username.toUpperCase()</span>
<p role="status">{result}</p>
</div>
{/if}
<div class="field">
<span class="caption">onvalueschange(changed, all), typed</span>
<p>{latest}</p>
</div>
<div class="field">
<span class="caption">form.getFieldValue('newsletter') is a boolean</span>
<p>{String(form.getFieldValue('newsletter'))}</p>
</div>
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
</style>
{
"username": "",
"email": "",
"subscribe": false
}<script lang="ts">
import { Button, Form, FormItem, Input, Switch, createForm } from 'svelte-ant-design';
interface Profile {
username: string;
email: string;
subscribe: boolean;
}
// Your own state: the form reads it and writes to it. `form` is only for its methods (the reset button).
const values: Profile = $state({ username: '', email: '', subscribe: false });
const form = createForm<Profile>();
let result = $state('');
</script>
<div class="stage">
<div class="sheet">
<Form
{form}
model={values}
name="model"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
rules={{
username: [
{ required: true, message: 'Please input a username' },
{ min: 3, message: 'At least 3 characters' }
]
}}
onfinish={(submitted) => (result = `Success: ${JSON.stringify(submitted)}`)}
>
<FormItem name="username" label="Username">
{#snippet children(field)}
<Input bind:value={values.username} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="email" label="Email" rules={[{ type: 'email', message: 'Not an email address' }]}>
{#snippet children(field)}
<Input bind:value={values.email} status={field.status} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem name="subscribe" label="Subscribe">
{#snippet children(field)}
<Switch bind:checked={values.subscribe} {...field.attrs} />
{/snippet}
</FormItem>
<FormItem wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
</div>
<div class="row">
<Button onclick={() => (values.username = 'ab')}>values.username = 'ab'</Button>
<Button onclick={() => form.setFieldValue('username', 'ann')}>setFieldValue('username', 'ann')</Button>
<Button onclick={() => form.resetFields()}>resetFields()</Button>
</div>
<div class="results">
<div class="field">
<span class="caption">values: your own $state object</span>
<pre>{JSON.stringify(values, null, 2)}</pre>
</div>
{#if result}
<div class="field">
<span class="caption">onfinish</span>
<p role="status">{result}</p>
</div>
{/if}
</div>
</div>
<style>
.stage {
display: grid;
gap: 16px;
width: 100%;
max-width: 660px;
margin-inline: auto;
}
.sheet {
padding: 28px 24px 4px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 12px;
background: var(--ads-color-bg-container);
box-shadow:
0 1px 2px rgba(16, 36, 94, 0.06),
0 6px 18px rgba(16, 36, 94, 0.05);
}
.field {
display: grid;
justify-items: start;
gap: 6px;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
font-weight: 500;
}
.results {
display: grid;
justify-items: start;
gap: 16px;
}
.results p {
margin: 0;
padding: 6px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 999px;
background: var(--ads-color-bg-container);
font-size: 13px;
}
.results pre {
box-sizing: border-box;
margin: 0;
max-width: 100%;
overflow-x: auto;
padding: 10px 14px;
border: 1px solid var(--ads-color-border-secondary);
border-radius: 10px;
background: var(--ads-color-bg-container);
font-size: 12px;
}
</style>
Form API
| Property | Description | Type | Default |
|---|---|---|---|
| form | The 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> | — |
| model | Your 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 | — |
| rules | The 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 | — |
| initialValues | The 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> | — |
| name | The prefix of the ids of the controls (signup_username). Left out: a unique id is used, so two forms never share ids. | string | — |
| layout | How an item lays out its label and control. | 'horizontal' | 'vertical' | 'inline' | 'horizontal' |
| labelCol | The 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> | — |
| wrapperCol | The control column, as the props of Col. Without a span it takes the room that is left. | ComponentProps<typeof Col> | — |
| labelAlign | The alignment of the label text. start and end follow the text direction. | 'start' | 'end' | 'end' |
| labelWrap | Whether a long label wraps instead of being cut. | boolean | false |
| colon | Whether a colon follows the label. Only in the horizontal layout; the room after the label stays without it. | boolean | true |
| requiredMark | The 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 |
| validateTrigger | The 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' |
| validateMessages | The templates of the generated messages, laid over the English defaults key by key. See the rule table for the variables. | FormValidateMessages | — |
| preserve | Whether a field keeps its value when its item is destroyed. The default of the items. | boolean | true |
| disabled | Handed to the controls by hand through field.disabled. The form itself disables nothing. | boolean | — |
| size | Handed to the controls by hand through field.size. | 'small' | 'medium' | 'large' | — |
| variant | Handed to the controls by hand through field.variant. | 'outlined' | 'borderless' | 'filled' | 'underlined' | — |
| tooltip | The default props of every label tooltip, and the icon. | FormTooltipConfig | — |
| scrollToFirstError | After 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 } |
| feedbackIcons | The icons of the items with hasFeedback, one snippet per status. | Partial<Record<FormValidateStatus, Snippet>> | — |
| classNames | Extra classes for the six parts of every item. | Partial<Record<root | label | content | help | helpItem | extra, string>> | — |
| styles | Inline styles for the six parts of every item. | Partial<Record<root | label | content | help | helpItem | extra, Record<string, string | number>>> | — |
| onfinish | Called 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 | — |
| onfinishfailed | Called after a submit that failed validation, with { values, errorFields, outOfDate }. | (info: FormFinishFailedInfo) => void | — |
| onvalueschange | Called 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 | — |
| onfieldschange | Called 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 | — |
| children | The items of the form. | Snippet | — |
| class | An additional CSS class. | string | — |
| style | Inline style of the <form>. | string | — |
| native attributes | Native <form> attributes except onsubmit (use onfinish). novalidate is set, because the rules validate; pass novalidate={false} to get the native validation back. | HTMLFormAttributes | — |
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
| Property | Description | Type | Default |
|---|---|---|---|
| name | Connects 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)[] | — |
| label | The 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 | — |
| rules | The rules of the field. A rule can be a function of the form that returns one, to compare with another field. | FormRule[] | — |
| required | The mark and aria-required. Left out: derived from a required rule; false turns the mark off. | boolean | — |
| help | Replaces the generated messages. Text or a snippet; false shows no message. | string | Snippet | false | — |
| extra | A hint below the control and the messages. Text or a snippet. | string | Snippet | — |
| tooltip | A 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 | — |
| hasFeedback | Gives 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 |
| validateStatus | Sets the status by hand; it wins over the validation. Left out: derived (validating, error, warning, and success with hasFeedback). | 'success' | 'warning' | 'error' | 'validating' | — |
| validateFirst | true 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 |
| validateTrigger | The events that validate this field. A rule's own validateTrigger must be a subset of it. | 'change' | 'blur' | ('change' | 'blur')[] | the form's |
| validateDebounce | Milliseconds to wait before a validation starts; a newer change replaces a waiting one. | number | — |
| dependencies | Fields 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)[])[] | — |
| initialValue | The value when the form has none; the initialValues of the form win. | unknown | — |
| hidden | Hides the item (display: none); the field is still collected and validated. | boolean | false |
| preserve | false removes the value when the item is destroyed. | boolean | the form's |
| messageVariables | Extra variables for the message templates. | Record<string, string> | — |
| colon / labelAlign / labelWrap / labelCol / wrapperCol | The same as on the form; the item's value wins. | as on the form | the form's |
| layout | The 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 |
| htmlFor | The for of the label. null removes it, so a click on the label does not reach the control (the control keeps its name). | string | null | the id of the control |
| children | The control. It receives the field object. An item with no name may hold any content. | Snippet<[FormField]> | — |
| class / style | Appended to the root. | string | — |
| native attributes | Native <div> attributes go to the root. | HTMLAttributes<HTMLDivElement> | — |
field: what an item hands to its control
| Property | Description | Type |
|---|---|---|
| value | The 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 |
| status | error or warning for the status prop of a control that has one (Input, Select); otherwise undefined. | 'error' | 'warning' | undefined |
| attrs | id, 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 / warnings | The messages of the field. | string[] |
| validating / touched | A validation is running; the user changed the field, or it was validated on blur. | boolean |
| disabled / size / variant | The values of the form, for the matching props of the control. undefined leaves the control's own default. | boolean | FormSize | FormVariant | undefined |
| feedback | The hasFeedback icon as a snippet, for a suffix of the control; undefined when there is none to show. | Snippet | undefined |
FormInstance methods
| Method | Description | Type |
|---|---|---|
| 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
| Property | Description | Type |
|---|---|---|
| required | The value must exist: undefined, null, an empty string and an empty array fail; 0, false and whitespace pass (add whitespace). | boolean |
| type | The 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 / max | The length of a string or array, the value of a number. len wins over a range. | number |
| pattern | The value must match. | RegExp |
| enum | With type: 'enum': the allowed values. | unknown[] |
| whitespace | With type: 'string': a value of only whitespace fails. | boolean |
| transform | Changes the value before it is checked. | (value) => any |
| message | The 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 |
| validator | A 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> |
| warningOnly | A failure is shown as a warning and does not stop the submit. | boolean |
| defaultField / fields | With type: 'array' or 'object': the rule of every element, or the rules of the keys. | FormRuleConfig | Record<string, FormRuleConfig> |
| validateTrigger | The events that run this rule: a subset of the trigger of the item. | 'change' | 'blur' | ('change' | 'blur')[] |
createForm and getFormInstance
| Method | Description | Type |
|---|---|---|
| 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
| Token | Description | Default |
|---|---|---|
| --ads-form-item-margin-bottom | The space after an item. A message of one line fits into it, so showing it moves nothing. | 24px |
| --ads-form-label-color | Colour of the label. | var(--ads-color-text) |
| --ads-form-label-font-size | Font size of the label and the star. | var(--ads-font-size) |
| --ads-form-required-mark-color | Colour of the star. | var(--ads-color-danger-text) |
| --ads-form-help-color | Colour of a neutral message. tokens-accessible.css darkens it to #666666. | var(--ads-color-text-tertiary) |
| --ads-form-extra-color | Colour of the extra hint and of (optional). tokens-accessible.css darkens it to #666666. | var(--ads-color-text-tertiary) |
| --ads-form-error-text | Colour of an error message. | var(--ads-color-danger-text) |
| --ads-form-warning-text | Colour of a warning message. tokens-accessible.css darkens it to #874d00. | #faad14 |
| --ads-form-success-icon | Colour of the success icon. tokens-accessible.css darkens it to #389e0d. | #52c41a |
| --ads-form-warning-icon | Colour of the warning icon. tokens-accessible.css darkens it to #ad6800. | #faad14 |
| --ads-form-error-icon | Colour of the error icon. | #ff4d4f |
| --ads-form-tooltip-icon-color | Colour 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 arearia-hiddenelements, not generated content, so the name of the control is the label text alone. The control also getsaria-labelledby(the label), so it keeps its name whenhtmlFor={null}stops a click on the label from reaching it. field.attrspointsaria-describedbyat the messages and the extra hint, and only at ids that exist;aria-invalidis set for an error only (a warning is described, not invalid);aria-requiredfollows the rules.- The messages are neither a live region nor
role="alert": a screen reader reads them througharia-describedbywhen 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.cssfor 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.