> For AI agents: the complete documentation index is available at https://rickyshin93.github.io/tao-ui/llms.txt, the full documentation bundle is available at https://rickyshin93.github.io/tao-ui/llms-full.txt.

# Form

Data Entry`@rockshin/tao-ui`

[Examples](#examples)[API](#api)

Collects and validates field values with an antd-aligned API (rules, dependencies, Form.List) on top of the rc-form engine.

## When to use

Use Form with Form.Item when fields need a value store, rule validation, or submit handling. Use the lighter FormField when you manage state yourself.

Direct Form.Item children have 4px bottom spacing when a feedback row is present (`--tao-size-unit`), or 20px otherwise (`--tao-padding-md`). `--tao-form-field-item-gap` overrides either default. Stack and FormSection manage spacing for items placed inside them. `noStyle` adds neither a shell nor spacing, and standalone FormField layout is unchanged.

At the default 12–14px message sizes, the reserved line is 18px high; with its 2px top margin and 4px trailing gap, feedback occupies 24px. Larger custom message text can increase the line height.

Form.Item reserves one feedback line when it has validation rules or an explicit `help`, `extra` or `validateStatus`. Single-line validation messages can appear or disappear without moving subsequent fields or buttons. Longer messages wrap and expand the space naturally to avoid overlapping content. Fields without validation or feedback do not reserve an empty row. Use `help=""` to keep the row when controlling messages manually.

**Recommended**

- Declare validation as rules on Form.Item; the required mark is inferred from rules.
- Use dependencies for cross-field rules such as password confirmation.
- Use Form.useForm() for imperative control (setFieldsValue, resetFields, submit).
- Values written through `setFields` — including the controlled `fields` prop —
  clear stale validation errors for fields whose value changed; include
  `errors`/`warnings` in the same entry to provide fresh validation state.
- Set size or disabled on Form to cascade them to every control inside.

**Avoid**

- Do not bind the same name in two mounted Form.Items.
- Do not mix manual value/onChange props with a bound Form.Item on the same control.

## Examples


### Basic usage
```tsx preview
import { useState } from 'react';
import { Button, Form, Input } from '@rockshin/tao-ui';

function FormExample() {
  const [feedback, setFeedback] = useState('');
  return (
    <>
      <Form
        initialValues={{ email: '' }}
        onFinish={(values) => setFeedback(JSON.stringify(values))}
        style={{ maxWidth: 400 }}
      >
        <Form.Item
          name="email"
          label="Email"
          rules={[{ required: true, message: 'Enter your email.' }]}
        >
          <Input placeholder="you@example.com" />
        </Form.Item>
        <Button type="submit">Create account</Button>
      </Form>
      <output
        aria-live="polite"
        style={{
          display: 'block',
          marginTop: 12,
          whiteSpace: 'pre-wrap',
          overflowWrap: 'anywhere',
        }}
      >
        {feedback}
      </output>
    </>
  );
}

export default FormExample;
```

### Validation
```tsx preview
import { useState } from 'react';
import { Button, Form, Input } from '@rockshin/tao-ui';

function ValidatedForm() {
  const [feedback, setFeedback] = useState('');
  return (
    <>
      <Form
        onFinish={(values) => setFeedback(JSON.stringify(values))}
        style={{ maxWidth: 420 }}
      >
        <Form.Item
          name="username"
          label="Username"
          rules={[
            { required: true, message: 'Enter a username.' },
            { min: 3, message: 'Use at least 3 characters.' },
          ]}
        >
          <Input placeholder="username" />
        </Form.Item>
        <Form.Item
          name="email"
          label="Email"
          rules={[{ required: true, message: 'Enter an email.' }]}
        >
          <Input type="email" placeholder="you@example.com" />
        </Form.Item>
        <Button type="submit">Submit</Button>
      </Form>
      <output
        aria-live="polite"
        style={{
          display: 'block',
          marginTop: 12,
          whiteSpace: 'pre-wrap',
          overflowWrap: 'anywhere',
        }}
      >
        {feedback}
      </output>
    </>
  );
}

export default ValidatedForm;
```

### Horizontal layout
```tsx preview
import { Button, Form, Input } from '@rockshin/tao-ui';

function HorizontalForm() {
  return (
    <Form layout="horizontal" style={{ maxWidth: 560 }}>
      <Form.Item name="name" label="Name">
        <Input placeholder="Project name" />
      </Form.Item>
      <Form.Item name="slug" label="Slug">
        <Input placeholder="project-name" />
      </Form.Item>
      <Button type="submit">Create project</Button>
    </Form>
  );
}

export default HorizontalForm;
```

### Complete form
Combine fields, sections, and actions into an end-to-end entry and submission flow.
```tsx preview
import {
  Button,
  FormActions,
  FormField,
  FormLayout,
  FormSection,
  Input,
  Select,
  Stack,
} from '@rockshin/tao-ui';

export default function FormCompleteForm() {
  return (
    <FormLayout>
      <FormSection
        title="Personal Information"
        description="Basic details about you."
      >
        <Stack direction="horizontal" gap="md">
          <FormField label="First name" required>
            <Input value="Rihua" />
          </FormField>
          <FormField label="Last name" required>
            <Input value="Chen" />
          </FormField>
        </Stack>
        <FormField label="Email" required>
          <Input value="rihua@example.com" prefix={<span>✉️</span>} />
        </FormField>
        <FormField label="Phone" description="Optional. Used for recovery.">
          <Input placeholder="138 0000 0000" prefix={<span>+86</span>} />
        </FormField>
      </FormSection>

      <FormSection title="Preferences" description="Configure your workspace.">
        <FormField label="Language">
          <Select
            options={[
              { label: '简体中文', value: 'zh' },
              { label: 'English', value: 'en' },
            ]}
            value="zh"
          />
        </FormField>
        <FormField label="Timezone">
          <Select
            options={[
              { label: 'Asia/Shanghai (UTC+8)', value: 'cst' },
              { label: 'America/New_York (UTC-5)', value: 'est' },
            ]}
            value="cst"
          />
        </FormField>
      </FormSection>

      <FormActions>
        <Button variant="ghost">Cancel</Button>
        <Button variant="primary">Save Changes</Button>
      </FormActions>
    </FormLayout>
  );
}
```

### Cross-field validation
Validate against another field and update feedback when the related value changes.
```tsx preview
import { Button, Form, FormActions, Input, Stack } from '@rockshin/tao-ui';

export default function FormFormCrossField() {
  return (
    <Form layout="horizontal" style={{ maxWidth: 460 }}>
      <Stack gap="md">
        <Form.Item
          name="password"
          label="Password"
          rules={[{ required: true, message: 'Password is required' }]}
        >
          <Input type="password" />
        </Form.Item>
        <Form.Item
          name="confirm"
          label="Confirm"
          dependencies={['password']}
          rules={[
            ({ getFieldValue }) => ({
              validator: (_, value) =>
                !value || getFieldValue('password') === value
                  ? Promise.resolve()
                  : Promise.reject(new Error('Passwords do not match')),
            }),
          ]}
        >
          <Input type="password" />
        </Form.Item>
        <FormActions>
          <Button type="submit" variant="primary">
            Change password
          </Button>
        </FormActions>
      </Stack>
    </Form>
  );
}
```

### Dynamic field lists
Add and remove repeated fields with `Form.List`, keeping form values and field indexes aligned.
```tsx preview
import { useState } from 'react';
import { Button, Form, FormActions, Input, Stack } from '@rockshin/tao-ui';

export default function FormFormDynamicList() {
  const [feedback, setFeedback] = useState('');
  return (
    <>
      <Form
        style={{ maxWidth: 400 }}
        initialValues={{ members: [''] }}
        onFinish={(values) => setFeedback(JSON.stringify(values, null, 2))}
      >
        <Stack gap="md">
          <Form.List name="members">
            {(fields, { add, remove }) => (
              <>
                {fields.map((field, index) => (
                  <Stack
                    key={field.key}
                    direction="horizontal"
                    gap="sm"
                    align="start"
                  >
                    <Form.Item
                      name={field.name}
                      label={index === 0 ? 'Members' : undefined}
                      noStyle={index !== 0}
                      rules={[{ required: true, message: 'Required' }]}
                    >
                      <Input placeholder="member name" />
                    </Form.Item>
                    <Button variant="ghost" onClick={() => remove(field.name)}>
                      Remove
                    </Button>
                  </Stack>
                ))}
                <Button variant="secondary" onClick={() => add()}>
                  Add member
                </Button>
              </>
            )}
          </Form.List>
          <FormActions>
            <Button type="submit" variant="primary">
              Save
            </Button>
          </FormActions>
        </Stack>
      </Form>
      <output
        aria-live="polite"
        style={{
          display: 'block',
          marginTop: 12,
          whiteSpace: 'pre-wrap',
          overflowWrap: 'anywhere',
        }}
      >
        {feedback}
      </output>
    </>
  );
}
```

### Scroll to a claim field
Get the instance with `Form.useForm()`, a Form ref, or `Form.useFormInstance()`. Array paths and full `Form.List` paths such as `['claims', 0, 'email']` are supported.
```tsx preview
import { Button, Form, Input } from '@rockshin/tao-ui';

export default function ScrollToClaimField() {
  const [form] = Form.useForm();
  return (
    <div style={{ height: 320, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <Button
        style={{ flexShrink: 0 }}
        onClick={() => form.scrollToField(['claimant', 'email'], {
          behavior: 'smooth', block: 'center', focus: true,
        })}
      >
        Reveal and focus email
      </Button>
      <Form form={form} style={{ minHeight: 0, flex: 1, overflowY: 'auto' }}>
        <p>Scroll down, or use the button to reveal the field.</p>
        <div aria-hidden="true" style={{ height: 360 }} />
        <Form.Item name={['claimant', 'email']} label="Claimant email">
          <Input placeholder="claim@example.com" />
        </Form.Item>
        <div aria-hidden="true" style={{ height: 160 }} />
      </Form>
    </div>
  );
}
```

Defaults to `scrollMode: 'if-needed'` and `block: 'nearest'`. Accepts `behavior`, `block`, `inline`, `boundary`, `scrollMode` and other scroll options; `focus: true` focuses the control after starting the scroll. Only mounted fields can be located; reveal conditional or unmounted tab content first. Custom controls must forward `ref` (a DOM node or an instance with `nativeElement`) or `id`.

```tsx
<Form
  form={form}
  onFinishFailed={({ errorFields }) => {
    if (errorFields.length) {
      form.scrollToField(errorFields[0].name, { focus: true });
    }
  }}
/>
```

## API


### [#](#form)Form



| Property | Description | Type | Default Value |
| --- | --- | --- | --- |
| layout | Label/control arrangement inherited by Form.Item. Defaults to 'vertical'. | `"vertical" | "horizontal" | undefined` | `-` |
| size | Cascades a control size to everything inside the form. | `TaoSize | undefined` | `-` |
| disabled | Disables every tao-ui control inside the form (e.g. while submitting). | `boolean | undefined` | `-` |

