Form表单
表单用于收集、校验并提交一组值。Form 负责绘制 <form>、布局与提交流程;FormItem 是包含标签、控件、消息与提示的一行。控件通过显式的 field 对象连接,因此任何控件都适用,也不会泄漏到弹层中。规则由 @rc-component/async-validator 检查;提交失败时焦点会移到第一个无效字段。
何时使用
- 需要收集信息,并按规则校验字段时使用。
- 即使没有校验规则,也可以用它来排布标签、控件、消息与提示。
- 只有一个字段、没有标签也没有规则时,直接使用控件更简单。
值的类型与自有模型
把值的形状作为类型参数传给 createForm:createForm<Signup>()。实例以及接收它的 Form 都据此获得类型:onfinish 收到的是 Signup,getFieldValue('age') 是数字,类型不符会导致编译错误。不传类型参数时一切保持宽松,即 Record<string, unknown>。表单项的名字没有类型。
<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. --> 示例: 带类型的表单
与 Vue 一样,值可以保存在你自己的对象中:把 $state 对象作为 model 传给 Form,并把控件绑定到它。该对象的类型就是值的类型,无需再声明别的。form 与 model 可以同时使用:此时实例只负责方法与字段的状态。
<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> 示例: 自己的数据模型
从外部对模型做的修改(被绑定的控件、代码中的赋值)会被视为用户的修改:字段会被标记为已触碰并校验。实例的方法(
setFieldValue、resetFields)不算。请传入 $state 对象:普通对象虽会被写入,但读取它的模板不会更新。代码演示
<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>
layout
<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>
labelAlign
labelWrap
colon
<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>
requiredMark
<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>
validateTrigger
validateDebounce 500
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>
validateFirst
<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>
validateStatus of the last item
<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.
onvalueschange (the user only), onfieldschange (calls)
none yet / 0
getFieldsValue(), getFieldsError(), isFieldsTouched()
{
"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>
scrollToFirstError
<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>
size
variant
disabled
<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>
getFieldsValue()
{}<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>
onvalueschange(changed, all), typed
nothing yet
form.getFieldValue('newsletter') is a boolean
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>
values: your own $state object
{
"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
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| form | 表单的存储对象,由 createForm() 创建。省略时表单会自行创建,并可通过 bind:form 取回。值的类型 Values 取自它。 | FormInstance<Values> | — |
| model | 由你自己持有的 $state 对象,字段的值就保存在其中:可以把控件绑定到 values.username 或 field.value。从外部对它做的修改(被绑定的控件、代码中的赋值)会被视为用户的修改:字段被标记为已触碰,触发 onvalueschange 并进行校验。实例的方法(setFieldValue、resetFields)不算。省略时由 store 自己保存值。请传入 $state 对象,否则读取它的模板不会更新。 | Values | — |
| rules | 按字段名给出的规则:每个名字一个列表,或用对象表示其下的名字({ user: { name: [rule] } })。同名表单项自己的规则排在它们之后,任一方的 required 都会显示必填标记。 | FormRules | — |
| initialValues | 字段的初始值,也是 resetFields 回到的值。不是响应式的:之后修改该属性不会生效(请使用 setFieldsValue)。被控件绑定的字段必须有初始值。设置了 model 时,只补全模型中缺少的键。 | DeepPartial<Values> | — |
| name | 控件 id 的前缀(signup_username)。省略时使用唯一 id,因此两个表单不会共用 id。 | string | — |
| layout | 每一项如何排布标签与控件。 | 'horizontal' | 'vertical' | 'inline' | 'horizontal' |
| labelCol | 标签列,使用 Col 的属性。单项自己的值优先。宽度不足 576 px 时,水平布局会把标签叠到控件上方,除非这里给出了 xs。 | ComponentProps<typeof Col> | — |
| wrapperCol | 控件列,使用 Col 的属性。不设 span 时占据剩余空间。 | ComponentProps<typeof Col> | — |
| labelAlign | 标签文字的对齐方式。start 与 end 跟随文字方向。 | 'start' | 'end' | 'end' |
| labelWrap | 长标签是否换行而不是被截断。 | boolean | false |
| colon | 标签后是否显示冒号。仅在水平布局下有效;不显示冒号时,标签后仍保留间距。 | boolean | true |
| requiredMark | 必填标记:显示、隐藏、可选标记,或一个自行绘制标签的 snippet。仅可在表单层面设置。 | boolean | 'optional' | Snippet<[{ label, required }]> | true |
| validateTrigger | 触发字段校验的事件:用户修改、控件失去焦点或两者。是各项的默认值。 | 'change' | 'blur' | ('change' | 'blur')[] | 'change' |
| validateMessages | 自动生成消息的模板,会逐项覆盖默认的英文文案。变量见规则表。 | FormValidateMessages | — |
| preserve | 字段对应的表单项被销毁时是否保留其值。是各项的默认值。 | boolean | true |
| disabled | 需要通过 field.disabled 手动传给控件。表单本身不会禁用任何内容。 | boolean | — |
| size | 需要通过 field.size 手动传给控件。 | 'small' | 'medium' | 'large' | — |
| variant | 需要通过 field.variant 手动传给控件。 | 'outlined' | 'borderless' | 'filled' | 'underlined' | — |
| tooltip | 所有标签提示的默认属性,以及图标。 | FormTooltipConfig | — |
| scrollToFirstError | 提交失败后:把第一个无效控件滚动到可见区域并聚焦。true 只滚动,对象形式还可传入原生滚动选项,false 则什么都不做。 | boolean | (ScrollIntoViewOptions & { focus?: boolean }) | { focus: true } |
| feedbackIcons | 带 hasFeedback 的各项所用的图标,每种状态一个 snippet。 | Partial<Record<FormValidateStatus, Snippet>> | — |
| classNames | 作用于每一项六个部分的额外类名。 | Partial<Record<root | label | content | help | helpItem | extra, string>> | — |
| styles | 作用于每一项六个部分的内联样式。 | Partial<Record<root | label | content | help | helpItem | extra, Record<string, string | number>>> | — |
| onfinish | 校验通过的提交之后调用,参数为各字段的值。其中只有带表单项的字段:可能被隐藏的字段(例如被 {#if} 隐藏)不会出现,请在 Values 中将其声明为可选(age?: number)。 | (values: Values) => void | — |
| onfinishfailed | 校验失败的提交之后调用,参数为 { values, errorFields, outOfDate }。 | (info: FormFinishFailedInfo) => void | — |
| onvalueschange | 用户修改值之后调用,参数为被修改的值和全部值。由代码设置的值不会触发。 | (changed: DeepPartial<Values>, all: Values) => void | — |
| onfieldschange | 字段的任何状态变化时调用:值、touched、validating、errors 或 warnings。一次校验会先报告 validating 为 true,再以 false 连同结果报告。 | (changed: FormFieldData[], all: FormFieldData[]) => void | — |
| children | 表单中的各项。 | Snippet | — |
| class | 附加的 CSS 类名。 | string | — |
| style | <form> 的内联样式。 | string | — |
| native attributes | 原生 <form> 属性,但不含 onsubmit(请使用 onfinish)。默认带 novalidate,因为校验由规则完成;传入 novalidate={false} 可恢复原生校验。 | HTMLFormAttributes | — |
与 Ant Design 的差异:控件通过显式的
field 对象连接(bind:value={field.value}),而不是克隆子元素,因此不需要 valuePropName、trigger、getValueFromEvent、getValueProps、normalize、shouldUpdate 与 useWatch(函数绑定可转换值,读取值本身就是响应式的),表单项的状态也不会泄漏到控件的弹层里。被控件绑定的字段必须有初始值。scrollToFirstError 默认开启。disabled、size、variant 与状态通过 field 传给控件,而不是通过上下文(上下文已列入计划)。labelAlign 取 start 与 end,validateTrigger 取 change 与 blur,规则的 message 是字符串。规则由 @rc-component/async-validator 检查,这是本包的第一个依赖。Form.List、Form.ErrorList、Form.Provider 与 noStyle 已列入计划。值可以带类型(createForm<Values>()),也可以保存在你自己的 $state 对象中(model,与 Vue 相同);规则还可以按字段名交给表单。FormItem 的 API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| name | 把表单项与字段关联:一个键,或一条路径(['user', 'city']、['users', 0, 'name'])。数字步骤会生成数组。省略时只是一个布局行。 | string | number | (string | number)[] | — |
| label | 标签:文本或 snippet。null 会保留标签列和冒号但不显示文字;省略时则没有标签列。 | string | Snippet | null | — |
| rules | 字段的校验规则。规则也可以是一个接收表单并返回规则的函数,用于与其他字段比较。 | FormRule[] | — |
| required | 必填标记与 aria-required。省略时由 required 规则推导;false 会关闭标记。 | boolean | — |
| help | 替换自动生成的消息。文本或 snippet;false 表示不显示任何消息。 | string | Snippet | false | — |
| extra | 控件和消息下方的附加提示。文本或 snippet。 | string | Snippet | — |
| tooltip | 标签后的帮助图标,点击或聚焦时打开 Tooltip:文本、snippet,或带 icon 与 iconLabel(图标的可访问名称,默认 More information)的 Tooltip 属性。 | string | Snippet | FormTooltipConfig | — |
| hasFeedback | 通过 field.feedback 给控件提供状态图标。对象形式可替换本项的图标。除非你放置 field.feedback,否则不会绘制任何内容。 | boolean | { icons: Partial<Record<FormValidateStatus, Snippet>> } | false |
| validateStatus | 手动指定状态,优先于校验结果。省略时自动推导(validating、error、warning,设置 hasFeedback 时还有 success)。 | 'success' | 'warning' | 'error' | 'validating' | — |
| validateFirst | true 在第一条失败的规则处停止。'parallel' 会同时运行所有规则,只保留第一条失败规则的消息。 | boolean | 'parallel' | false |
| validateTrigger | 触发本字段校验的事件。规则自己的 validateTrigger 必须是它的子集。 | 'change' | 'blur' | ('change' | 'blur')[] | the form's |
| validateDebounce | 校验开始前等待的毫秒数;更新的修改会取代正在等待的校验。 | number | — |
| dependencies | 用户修改这些字段时,会重新校验本字段(前提是它被操作过或已校验过)。由代码设置的值不会触发。 | (string | number | (string | number)[])[] | — |
| initialValue | 表单没有该值时使用的值;表单的 initialValues 优先。 | unknown | — |
| hidden | 隐藏该项(display: none);字段仍会被收集和校验。 | boolean | false |
| preserve | false 表示表单项被销毁时移除其值。 | boolean | the form's |
| messageVariables | 消息模板可使用的额外变量。 | Record<string, string> | — |
| colon / labelAlign / labelWrap / labelCol / wrapperCol | 与表单上的同名属性相同;单项的值优先。 | as on the form | the form's |
| layout | 本项的布局。inline 是整个表单的布局,因此这里不提供。 | 'horizontal' | 'vertical' | the form's |
| htmlFor | 标签的 for。null 会移除它,点击标签就不会影响控件(控件仍保留其名称)。 | string | null | the id of the control |
| children | 控件。它会收到 field 对象。没有 name 的表单项可以放任意内容。 | Snippet<[FormField]> | — |
| class / style | 附加到根元素。 | string | — |
| native attributes | 原生 <div> 属性会传给根元素。 | HTMLAttributes<HTMLDivElement> | — |
field:表单项传给控件的对象
| 属性 | 说明 | 类型 |
|---|---|---|
| value | 字段的值。setter 就是用户修改的路径:它保存值、标记 touched、进行校验,并触发 onvalueschange 与依赖字段。请这样绑定:bind:value={field.value}。 | any |
| status | 提供给带 status 属性的控件(Input、Select):error 或 warning,否则为 undefined。 | 'error' | 'warning' | undefined |
| attrs | id、aria-describedby(存在消息与附加提示时)、aria-invalid(出错时)、aria-required 与 aria-labelledby(标签)。请展开到控件上:{...field.attrs}。 | Record<string, string> |
| errors / warnings | 字段的消息。 | string[] |
| validating / touched | 正在校验;用户修改过该字段,或它在失焦时被校验过。 | boolean |
| disabled / size / variant | 表单上的对应值,用于控件的同名属性。undefined 表示保留控件自己的默认值。 | boolean | FormSize | FormVariant | undefined |
| feedback | hasFeedback 的图标,以 snippet 形式提供给控件的 suffix;没有可显示的图标时为 undefined。 | Snippet | undefined |
FormInstance 的方法
| 方法 | 说明 | 类型 |
|---|---|---|
| getFieldValue(name) | 字段的值。它是实时的值:修改前请先复制。在标记、$derived 或 $effect 中读取时会被追踪。 | (name) => unknown |
| getFieldsValue(names?, { filter }?) | 以嵌套对象返回值:默认是有表单项的字段;true 返回存储中的全部值;传名称列表则返回这些字段;filter 接收 { touched, validating }。类型:true 得到完整的 Values,其余形式得到深度 partial,使用字段前请先检查。 | (names: true) => Values; (names?: name[], options?) => DeepPartial<Values> |
| setFieldValue(name, value) | 设置值并清除该字段的消息。它不算用户修改:不触发回调、校验或依赖字段。 | (name, value) => void |
| setFieldsValue(values) | 把值深度合并进存储,并清除受影响字段的消息。数组会被整体替换。 | (values) => void |
| getFieldError(name) / getFieldWarning(name) | 单个字段的错误或警告消息。 | (name) => string[] |
| getFieldsError(names?) | 每个字段(或指定字段)的 { name, errors, warnings }。 | (names?) => FormFieldError[] |
| isFieldTouched(name) / isFieldsTouched(names?, allTouched?) / isFieldValidating(name) | 字段的状态标志。isFieldsTouched 在任意(设置 allTouched 时为全部)所列字段被操作过时为 true。 | (…) => boolean |
| setFields(fields) | 设置字段的值、touched、validating、errors 与 warnings 中的任意项。errors: [] 会清除消息。 | (fields: FormFieldData[]) => void |
| validateFields(names?, config?) | 校验有表单项的字段(或指定字段),并返回它们的值(只包含带表单项的字段,与 onfinish 相同);失败时以 { values, errorFields, outOfDate } 拒绝。只有警告的字段不算失败。config:validateOnly(不显示任何内容)、recursive(路径之下的字段)、dirty(仅被操作或已校验的字段)。 | (names?, config?) => Promise<values> |
| resetFields(names?) | 回到初始值(全部字段或指定字段),并清除 touched 标记与消息。 | (names?) => void |
| submit() | 等同于点击提交按钮:先校验,再调用 onfinish 或 onfinishfailed。需要已挂载的 Form。 | () => void |
| scrollToField(name, options?) | 把字段的控件滚动到可见区域(原生选项),传入 { focus: true } 时还会聚焦。 | (name, options?) => void |
规则的键
| 属性 | 说明 | 类型 |
|---|---|---|
| required | 值必须存在:undefined、null、空字符串和空数组不通过;0、false 与纯空白可通过(需要时加 whitespace)。 | boolean |
| type | 值的类型,未设置时为 string:string、number、boolean、integer、float、array、object、enum、url、email、tel、date、regexp、hex、method、any。 | FormRuleType |
| len / min / max | 字符串或数组的长度,数字的值。len 优先于范围。 | number |
| pattern | 值必须匹配该正则。 | RegExp |
| enum | 配合 type: 'enum':允许的取值。 | unknown[] |
| whitespace | 配合 type: 'string':只含空白的值不通过。 | boolean |
| transform | 在检查之前转换值。 | (value) => any |
| message | 错误文案:字符串,按模板处理。${name} 为标签(或字段名),其余为规则中的值;\${ 会保留为文本。省略时使用自动生成的消息。 | string |
| validator | 自定义检查:什么都不返回表示通过;抛出异常、reject,或返回 false、错误对象来表示失败。它与规则的其他键一起运行。 | (rule, value) => void | Promise<void> |
| warningOnly | 失败时只显示为警告,不会阻止提交。 | boolean |
| defaultField / fields | 配合 type: 'array' 或 'object':每个元素的规则,或各个键的规则。 | FormRuleConfig | Record<string, FormRuleConfig> |
| validateTrigger | 运行此规则的事件:是表单项触发时机的子集。 | 'change' | 'blur' | ('change' | 'blur')[] |
createForm 与 getFormInstance
| 方法 | 说明 | 类型 |
|---|---|---|
| createForm() | 创建表单的存储对象:它保存各字段的值与状态。把它传给 <Form {form}>,即可在任何地方调用其方法。传入值的形状 createForm<Signup>(),getFieldValue、setFieldValue、setFieldsValue、validateFields 以及表单的回调就都有了类型。它不接收参数:初始值是 Form 的属性。 | <Values extends object>() => FormInstance<Values> |
| getFormInstance() | 返回最近的 Form 的实例,供其内部组件(自定义控件、重置按钮等)使用。请在组件初始化时调用;在 Form 之外调用会抛出异常。 | <Values extends object>() => FormInstance<Values> |
设计令牌
| 令牌 | 说明 | 默认值 |
|---|---|---|
| --ads-form-item-margin-bottom | 每一项之后的间距。一行消息正好放进其中,因此显示消息不会让任何内容移动。 | 24px |
| --ads-form-label-color | 标签颜色。 | var(--ads-color-text) |
| --ads-form-label-font-size | 标签与星号的字号。 | var(--ads-font-size) |
| --ads-form-required-mark-color | 星号颜色。 | var(--ads-color-danger-text) |
| --ads-form-help-color | 中性消息的颜色。tokens-accessible.css 会将其加深为 #666666。 | var(--ads-color-text-tertiary) |
| --ads-form-extra-color | extra 提示与 (optional) 的颜色。tokens-accessible.css 会将其加深为 #666666。 | var(--ads-color-text-tertiary) |
| --ads-form-error-text | 错误消息的颜色。 | var(--ads-color-danger-text) |
| --ads-form-warning-text | 警告消息的颜色。tokens-accessible.css 会将其加深为 #874d00。 | #faad14 |
| --ads-form-success-icon | 成功图标的颜色。tokens-accessible.css 会将其加深为 #389e0d。 | #52c41a |
| --ads-form-warning-icon | 警告图标的颜色。tokens-accessible.css 会将其加深为 #ad6800。 | #faad14 |
| --ads-form-error-icon | 错误图标的颜色。 | #ff4d4f |
| --ads-form-tooltip-icon-color | 标签帮助图标的颜色。tokens-accessible.css 会将其加深为 #737373。 | var(--ads-color-text-tertiary) |
无障碍
- 标签是原生的
<label for>。星号与冒号是带aria-hidden的元素,而不是生成内容,因此控件的名称仅为标签文字。控件还会获得aria-labelledby(指向标签),所以即使htmlFor={null}阻止了点击标签聚焦控件,名称也依然保留。 field.attrs会让aria-describedby指向消息与 extra 提示,且只指向真实存在的 id;aria-invalid仅在出错时设置(警告会被描述,但不算无效);aria-required跟随规则。- 消息既不是 live 区域,也没有
role="alert":控件获得焦点时,读屏软件通过aria-describedby读出它们。提交失败的提示来自把焦点移到第一个无效字段(scrollToFirstError,默认开启)。若你关闭它,请自行告知用户提交失败。 - 标签的帮助图标是标签后的一个按钮:可用 Tab 到达,聚焦和悬停时打开提示,按 Escape 关闭。请用
iconLabel为它设置你所用语言的名称。 - 在每次修改时运行的校验会等输入法组合结束,因此不会在写了一半的音节下出现消息;组合结束时才进行校验。
- 状态绝不只靠颜色表达:星号和消息是文字,各状态图标的形状也不同。在 forced-colors 模式下,其余颜色由系统色替换。引入
tokens-accessible.css可让消息与图标达到 WCAG AA。 - 尚未验证:NVDA、JAWS 与 VoiceOver,手机上真实的输入法键盘,以及 Chromium 模拟之外的真实触摸设备。Orca 与 Firefox 由自动化测试验证。