# Form

> A native form boundary that submits values and shows field errors.

```tsx title="hero.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
import * as React from 'react'

type AppSettingsValues = {
  appName: string
  description: string
}

export function FormHeroDemo() {
  const [saved, setSaved] = React.useState<AppSettingsValues | null>(null)

  return (
    <Form<AppSettingsValues>
      aria-label="App settings"
      className="grid w-full max-w-96 gap-4"
      onChange={() => {
        if (saved) setSaved(null)
      }}
      onFormSubmit={(values) => setSaved(values)}
    >
      <Field name="appName">
        <FieldLabel>App name</FieldLabel>
        <Input
          required
          defaultValue="Customer support bot"
          placeholder="e.g. Research agent"
          autoComplete="off"
        />
        <FieldError match="valueMissing">Enter an app name.</FieldError>
      </Field>
      <Field name="description">
        <FieldLabel>Description</FieldLabel>
        <Textarea
          rows={2}
          defaultValue="Answers billing and plan questions from the help center."
          placeholder="e.g. Summarizes support tickets and suggests replies."
        />
        <FieldDescription>Optional summary visible to workspace members.</FieldDescription>
      </Field>
      <div className="flex justify-end">
        <Button type="submit" variant="primary">
          Save changes
        </Button>
      </div>
      <p
        role="status"
        className={
          saved ? 'min-w-0 system-xs-regular wrap-break-word text-text-tertiary' : 'sr-only'
        }
      >
        {saved
          ? saved.description.trim()
            ? `Saved ${saved.appName} — ${saved.description.trim()}`
            : `Saved ${saved.appName}`
          : ''}
      </p>
    </Form>
  )
}
```

## Usage guidelines

- Wrap every group of controls that saves together in a real form. `Form` renders a native `<form>`; use it when the boundary needs `onFormSubmit` values, server `errors`, `validationMode` or `actionsRef`. A native `<form>` stays correct when another form library owns submission and validation. Do not nest form owners.
- Give every submit button `type="submit"` and keep it enabled while the form is incomplete: submitting runs validation and marks the fields. Show `loading` on the button while the request is pending.
- Put a `name` on each [`Field`](/components/field.md). The names are the keys of the values object passed to `onFormSubmit` and of the `errors` object.
- Report a rejected submission at the field it concerns: map a documented error code to that field's message in `errors`, rather than showing the raw server message or a toast. A rejection that belongs to no field stays inside the form as an [`Alert`](/components/alert.md).
- Keep drafts, schemas and reset behavior in the application owner. Prefer uncontrolled controls with `defaultValue` unless application code must own the value while editing.
- Name each form with `aria-label` or `aria-labelledby` when a page has more than one.

Single fields are covered on [Field](/components/field.md) and grouped controls on [Fieldset](/components/fieldset.md).

## Anatomy

```tsx
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { Button } from '@langgenius/dify-ui/button'
```

```tsx
<Form>
  <Field>
    <FieldLabel />
    <Input />
    <FieldError />
  </Field>
  <Button type="submit" />
</Form>
```

## Examples

### Submitting values

`onFormSubmit` receives the values as an object keyed by field `name`, and calls `preventDefault` on the native submit event. With the default `validationMode="onSubmit"`, submitting validates every field first:

1. Native constraints run, then each `validate` function.
2. When a field is invalid, its `FieldError` shows, the control gets `aria-invalid`, focus moves to the first invalid control, and `onFormSubmit` is not called.
3. After the first submission, every field validates on each change: an error clears as soon as the value is fixed, and emptying a required field shows its error right away.

Submit the empty form to see the flow, then fill it in to see the submitted values.

```tsx title="submit.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
import {
  Field,
  FieldDescription,
  FieldError,
  FieldItem,
  FieldLabel,
} from '@langgenius/dify-ui/field'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'

type ApiKeyValues = {
  name: string
  scopes: string[]
}

const scopes = [
  { label: 'Run apps', value: 'apps:run' },
  { label: 'Read conversations', value: 'conversations:read' },
  { label: 'Manage knowledge', value: 'datasets:write' },
]

export function FormSubmitDemo() {
  const [submitted, setSubmitted] = React.useState<ApiKeyValues>()

  return (
    <div className="grid w-full max-w-96 gap-4">
      <Form<ApiKeyValues>
        aria-label="Create API key"
        className="grid gap-4"
        onSubmitCapture={() => setSubmitted(undefined)}
        onFormSubmit={(values) => setSubmitted(values)}
      >
        <Field name="name">
          <FieldLabel>Key name</FieldLabel>
          <Input required autoComplete="off" placeholder="e.g. Production runner" />
          <FieldDescription>Only visible to workspace admins.</FieldDescription>
          <FieldError match="valueMissing">Enter a key name.</FieldError>
        </Field>
        <Field
          name="scopes"
          validate={(value) =>
            Array.isArray(value) && value.length > 0 ? null : 'Choose at least one scope.'
          }
        >
          <Fieldset render={<CheckboxGroup defaultValue={[]} />} className="grid gap-1.5">
            <FieldsetLegend>Scopes</FieldsetLegend>
            {scopes.map((scope) => (
              <FieldItem key={scope.value}>
                <FieldLabel className="flex items-center gap-2">
                  <Checkbox value={scope.value} />
                  {scope.label}
                </FieldLabel>
              </FieldItem>
            ))}
          </Fieldset>
          <FieldError />
        </Field>
        <div className="flex justify-end">
          <Button type="submit" variant="primary">
            Create key
          </Button>
        </div>
      </Form>
      {submitted && (
        <output className="rounded-lg bg-background-section p-3 font-mono system-xs-regular wrap-break-word whitespace-pre-wrap text-text-secondary">
          {JSON.stringify(submitted, null, 2)}
        </output>
      )}
    </div>
  )
}
```

### Server errors

Pass `errors` to map a rejected request to fields by `name`. The error shows at once in a `FieldError` without `match`, the control becomes invalid and receives focus, and the error clears when the user edits that field. Submitting again without an edit keeps the error and does not call `onFormSubmit`. Save with the default key to see the rejection, then enter a key that starts with `sk-`.

```tsx title="server-errors.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'

type CredentialValues = {
  baseUrl: string
  apiKey: string
}

function saveCredentials(values: CredentialValues, signal: AbortSignal) {
  return new Promise<{ code: 'invalid_api_key' | 'ok' }>((resolve, reject) => {
    const timer = setTimeout(() => {
      if (!values.apiKey.startsWith('sk-')) resolve({ code: 'invalid_api_key' })
      else resolve({ code: 'ok' })
    }, 800)

    signal.addEventListener(
      'abort',
      () => {
        clearTimeout(timer)
        reject(new DOMException('Aborted', 'AbortError'))
      },
      { once: true },
    )
  })
}

export function FormServerErrorsDemo() {
  const [errors, setErrors] = React.useState<Record<string, string>>({})
  const [status, setStatus] = React.useState<'idle' | 'saving' | 'saved'>('idle')
  const controllerRef = React.useRef<AbortController | null>(null)

  React.useEffect(() => () => controllerRef.current?.abort(), [])

  async function submit(values: CredentialValues) {
    if (status === 'saving') return
    controllerRef.current?.abort()
    const controller = new AbortController()
    controllerRef.current = controller
    setStatus('saving')
    try {
      const result = await saveCredentials(values, controller.signal)
      if (result.code === 'invalid_api_key') {
        setErrors({ apiKey: 'OpenAI rejected this key. Check that it is active.' })
        setStatus('idle')
        return
      }
      setErrors({})
      setStatus('saved')
    } catch (error) {
      if (error instanceof DOMException && error.name === 'AbortError') return
      setStatus('idle')
    }
  }

  return (
    <Form<CredentialValues>
      aria-label="OpenAI credentials"
      className="grid w-full max-w-96 gap-4"
      errors={errors}
      onChange={() => {
        if (status === 'saved') setStatus('idle')
      }}
      onFormSubmit={(values) => void submit(values)}
    >
      <Field name="baseUrl">
        <FieldLabel>API base URL</FieldLabel>
        <Input
          type="url"
          required
          defaultValue="https://api.openai.com/v1"
          placeholder="https://api.example.com/v1"
          autoComplete="off"
          autoCapitalize="none"
          autoCorrect="off"
          spellCheck={false}
        />
        <FieldError match="valueMissing">Enter the API base URL.</FieldError>
        <FieldError match="typeMismatch">
          Enter a valid URL, such as https://api.openai.com/v1.
        </FieldError>
      </Field>
      <Field name="apiKey" validate={(value) => (value ? null : 'Enter an API key.')}>
        <FieldLabel>API key</FieldLabel>
        <Input
          defaultValue="openai-key-2291"
          placeholder="sk-…"
          autoComplete="off"
          autoCapitalize="none"
          autoCorrect="off"
          spellCheck={false}
        />
        <FieldDescription>Keys start with sk-.</FieldDescription>
        <FieldError />
      </Field>
      <div className="flex items-center justify-between gap-3">
        <span role="status" className="min-w-0 truncate system-xs-regular text-text-success">
          {status === 'saved' ? 'Credentials saved' : ''}
        </span>
        <Button type="submit" variant="primary" loading={status === 'saving'}>
          Save
        </Button>
      </div>
    </Form>
  )
}
```

### Validation timing

`validationMode` on `Form` sets when fields validate; a `validationMode` on a `Field` takes precedence. With `onBlur`, a field validates when focus leaves it; an empty required field is flagged only after the user has edited it, and typing hides the error until the next blur. `onChange` validates on every change. In every mode, submitting validates all fields, including untouched required ones. Switch between the modes below to compare when errors appear and clear.

```tsx title="validation-mode.tsx"
import type { FormProps } from '@langgenius/dify-ui/form'
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
import * as React from 'react'

type ValidationMode = NonNullable<FormProps['validationMode']>

const modes: ValidationMode[] = ['onSubmit', 'onBlur', 'onChange']

export function FormValidationModeDemo() {
  const [mode, setMode] = React.useState<ValidationMode>('onBlur')
  const [invitedEmail, setInvitedEmail] = React.useState<string>()
  const modeLabelId = React.useId()

  return (
    <div className="grid w-full max-w-96 gap-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <span id={modeLabelId} className="system-xs-medium text-text-tertiary">
          Validation mode
        </span>
        <SegmentedControl<ValidationMode>
          aria-labelledby={modeLabelId}
          value={mode}
          onValueChange={(nextMode) => {
            setMode(nextMode)
            setInvitedEmail(undefined)
          }}
        >
          {modes.map((option) => (
            <SegmentedControlItem key={option} value={option}>
              {option}
            </SegmentedControlItem>
          ))}
        </SegmentedControl>
      </div>
      <Form<{ email: string; displayName: string }>
        key={mode}
        aria-label="Invite member"
        validationMode={mode}
        className="grid gap-4"
        onChange={() => {
          if (invitedEmail) setInvitedEmail(undefined)
        }}
        onSubmitCapture={() => setInvitedEmail(undefined)}
        onFormSubmit={(values) => setInvitedEmail(values.email)}
      >
        <Field name="email">
          <FieldLabel>Email</FieldLabel>
          <Input
            type="email"
            required
            placeholder="name@example.com"
            autoComplete="off"
            autoCapitalize="none"
            autoCorrect="off"
            spellCheck={false}
          />
          <FieldError match="valueMissing">Enter an email address.</FieldError>
          <FieldError match="typeMismatch">
            Enter an email address like name@example.com.
          </FieldError>
        </Field>
        <Field name="displayName">
          <FieldLabel>Display name</FieldLabel>
          <Input required maxLength={30} placeholder="e.g. Ada Lovelace" autoComplete="off" />
          <FieldError match="valueMissing">Enter a display name.</FieldError>
        </Field>
        <div className="flex items-center justify-between gap-3">
          <span role="status" className="min-w-0 truncate system-xs-regular text-text-tertiary">
            {invitedEmail ? `Invitation sent to ${invitedEmail}` : ''}
          </span>
          <Button type="submit" variant="primary">
            Send invite
          </Button>
        </div>
      </Form>
    </div>
  )
}
```

## Keyboard

| Key     | Action                                                                                                    |
| ------- | --------------------------------------------------------------------------------------------------------- |
| `Enter` | In a text input, submits the form. Invalid fields show their errors and focus moves to the first of them. |

## API reference

### Form

A native form element with consolidated client and server error handling. Renders a `<form>` element.

Inherits `className`, `render`, `style`, `validationMode`, `errors`, `onFormSubmit`, `actionsRef` from [Base UI Form](https://base-ui.com/react/components/form).
