---
title: Form
description: Bind schema fields, validation, submission, and reset through createForm.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# Form

> Bind schema fields, validation, submission, and reset through createForm.

The controls below configure the `form.Field` wrappers inside the form. To explore the label,
description, help, and error slots, use the [Field playground](https://moraine.subf.dev/components/field.md).

## Anatomy

```text
form.Form [component; slot=root; <form>]
└── form.Field [part]
```

Each `form.Field` uses the [Field](https://moraine.subf.dev/components/field.md) layout; the bound `form.Form` owns only its
native form root.

## Usage

Use `createForm` for schema validation, submission, and reset. It returns a reactive Formisch store
with bound `form.Form` and `form.Field` components. Use standalone [Field](https://moraine.subf.dev/components/field.md)
when you only need labels and messages.

```tsx
import { createForm, Input, Button, Switch, InputGroup, Icon } from 'moraine'
import * as v from 'valibot'

const schema = v.object({
  email: v.pipe(v.string(), v.email('Enter a valid email address')),
  enabled: v.boolean(),
})

export function NotificationForm() {
  const form = createForm({
    schema,
    initialInput: { email: '', enabled: false },
  })

  return (
    <form.Form onSubmit={(output) => console.log(output)}>
      <form.Field name="email" label="Email Address">
        <InputGroup>
          <InputGroup.Leading>
            <Icon name="i-lucide:mail" />
          </InputGroup.Leading>
          <Input />
        </InputGroup>
      </form.Field>
      <form.Field name="enabled" label="Enable Notifications">
        <Switch />
      </form.Field>
      <Button type="submit">Save Changes</Button>
    </form.Form>
  )
}
```

### Submission

`form.Form` renders Formisch's `Form`: it prevents native navigation, validates the schema, focuses
the first invalid field in schema order, and calls `onSubmit` with the validated schema output
(after any Valibot transforms) and the native `SubmitEvent`. An invalid submit does not call
`onSubmit`. Native `action` and `method` attributes do not enable a browser navigation submit. The
returned store also supports Formisch's public methods and helpers, including `submit(form)` and
programmatic field focus.

`form.isSubmitting` stays `true` until a promise returned by `onSubmit` settles. A thrown or
rejected error is stored in the form `errors` rather than propagating; an error without a `message`
is recorded as the `unknownError` translation. `form.Form` does not disable child controls during
submission, so derive button loading or disabled state from `form.isSubmitting`.

```tsx
<Button type="submit" loading={form.isSubmitting} disabled={form.isSubmitting}>
  Save draft
</Button>
```

### Root styling

`<form.Form>` owns only its native form root, exposed as the `root` slot. Use `class` and `style`
(or `classes={{ root }}` and `styles={{ root }}`) for an individual form, or configure `form.base.root`
in your Theme. The root sets `data-submitting` while `form.isSubmitting` is `true`. Style the parts
of a field through the slot maps on `form.Field`.

### Bound field outside the form root

`form.Field` captures the Formisch store from `createForm()`, so it works without rendering
`form.Form`. Use the standalone [`Field`](https://moraine.subf.dev/components/field.md) when schema binding is not needed.

```tsx
const form = createForm({ schema })

<form.Field name="email" label="Email">
  <Input />
</form.Field>
```

### Field labels and messages

`<form.Field>` accepts every [Field](https://moraine.subf.dev/components/field.md) prop except `name`, which takes a schema
path: `label`, `hint`, `description`, `help`, `required`, `orientation`, and so on. Its error is the
first schema error unless you pass `error`. Moraine controls link descriptions and error messages
through ARIA attributes.

```tsx
<form.Field
  name="repoName"
  label="Repository name"
  description="Must be URL-friendly and unique within your organization."
  required
>
  <Input placeholder="moraine-app" />
</form.Field>
```

### Nested and array paths

Target nested object and array fields with a path array such as `['profile', 'email']` or
`['tags', 0]`. Path types are validated and autocompleted from the schema. A dotted string like
`'profile.email'` is read as one top-level key, not a path.

```tsx
<form.Field name={['profile', 'email']} label="Profile Email">
  <Input type="email" />
</form.Field>
```

### Reset

A `type="reset"` button restores the initial store input snapshot and clears validation metadata.
The restore runs in a microtask after the `reset` event and is skipped if a handler calls
`event.preventDefault()`. Handle `onReset` on `form.Form` when your code needs to react to it.

```tsx
<form.Form onReset={() => setResetCount((count) => count + 1)}>
  <form.Field name="name" label="Name">
    <Input />
  </form.Field>
  <Button type="reset" variant="outline">
    Reset
  </Button>
</form.Form>
```

## Examples

### Save a username

Define a schema and `initialInput`, then render the bound `form.Form` and `form.Field`. Submit
receives the validated output.

```tsx
import { Button, createForm, Input } from 'moraine'
import { createSignal, Show } from 'solid-js'
import * as v from 'valibot'

const schema = v.object({
  username: v.pipe(v.string(), v.nonEmpty('Username is required')),
})

export function BasicForm() {
  const [submitted, setSubmitted] = createSignal<string | null>(null)
  const form = createForm({ schema, initialInput: { username: '' } })

  return (
    <div class="max-w-md w-full space-y-4">
      <form.Form
        onSubmit={(values) => {
          setSubmitted(values.username)
        }}
        class="space-y-4"
      >
        <form.Field name="username" label="Username" required>
          <Input placeholder="Enter username" />
        </form.Field>
        <Button type="submit">Save Profile</Button>
      </form.Form>
      <Show when={submitted()}>
        <p class="text-xs text-muted-foreground">
          Profile saved for user: <span class="text-foreground font-medium">{submitted()}</span>
        </p>
      </Show>
    </div>
  )
}
```

### Configure field copy

Set `label`, `hint`, `description`, `help`, and `required` on `form.Field`. Pass `error` only when
the page or server supplies a message outside the schema.

```tsx
import { createForm, Input } from 'moraine'
import * as v from 'valibot'

export function LabelsMessages() {
  const form = createForm({
    schema: v.object({
      repoName: v.string(),
      deploymentTarget: v.string(),
    }),
    initialInput: { repoName: '', deploymentTarget: 'prod-us-east-1' },
  })

  return (
    <div class="max-w-md w-full space-y-4">
      <form.Field
        name="repoName"
        label="Repository name"
        description="Must be URL-friendly and unique within your organization."
        required
      >
        <Input placeholder="moraine-app" />
      </form.Field>

      <form.Field
        name="deploymentTarget"
        label="Deployment target"
        error="Selected cluster is currently unreachable."
      >
        <Input />
      </form.Field>
    </div>
  )
}
```

### Lay out a settings panel

Set `orientation="horizontal"` so the label sits beside the control.

```tsx
import { createForm, Input, Select } from 'moraine'
import * as v from 'valibot'

export function HorizontalLayout() {
  const form = createForm({
    schema: v.object({
      displayName: v.string(),
      role: v.string(),
    }),
    initialInput: { displayName: '', role: '' },
  })

  return (
    <div class="mx-auto max-w-2xl w-full space-y-4">
      <form.Field
        name="displayName"
        orientation="horizontal"
        label="Display Name"
        description="Public name shown in activity feeds."
      >
        <Input placeholder="Moraine Team" />
      </form.Field>

      <form.Field name="role" orientation="horizontal" label="Default Role" required>
        <Select
          items={[
            { label: 'Developer', value: 'developer' },
            { label: 'Designer', value: 'designer' },
            { label: 'Manager', value: 'manager' },
          ]}
          placeholder="Select role"
        />
      </form.Field>
    </div>
  )
}
```

### Edit nested profile fields

Pass a path tuple such as `['profile', 'email']` when the schema nests objects.

```tsx
import { Button, createForm, Input } from 'moraine'
import * as v from 'valibot'

export function NestedPath() {
  const form = createForm({
    schema: v.object({
      profile: v.object({
        name: v.pipe(v.string(), v.nonEmpty('Name is required.')),
        email: v.pipe(v.string(), v.email('Valid email is required.')),
      }),
    }),
    initialInput: { profile: { name: '', email: '' } },
  })

  return (
    <form.Form class="mx-auto max-w-xl w-full space-y-4">
      <form.Field name={['profile', 'name']} label="Profile Name" required>
        <Input placeholder="Moraine Team" />
      </form.Field>

      <form.Field name={['profile', 'email']} label="Profile Email" required>
        <Input type="email" placeholder="team@acme.dev" />
      </form.Field>

      <Button type="submit">Save Profile</Button>
    </form.Form>
  )
}
```

### Save a draft with loading

Read `form.isSubmitting` for the submit button. The form does not disable nested controls on its
own.

```tsx
import { Button, createForm, Input } from 'moraine'
import { Show, createSignal } from 'solid-js'
import * as v from 'valibot'

const schema = v.object({ title: v.pipe(v.string(), v.nonEmpty('A title is required.')) })

function saveDraft(): Promise<void> {
  return new Promise((resolve) => window.setTimeout(resolve, 2000))
}

export function AsyncSubmit() {
  const [saved, setSaved] = createSignal(false)
  const form = createForm({ schema, initialInput: { title: '' } })
  const handleSubmit = async () => {
    setSaved(false)
    await saveDraft()
    setSaved(true)
  }

  return (
    <form.Form onSubmit={handleSubmit} class="max-w-sm space-y-4">
      <form.Field name="title" label="Draft title" required>
        <Input placeholder="Quarterly update" />
      </form.Field>
      <Button
        type="submit"
        leading="i-lucide:save"
        loading={form.isSubmitting}
        disabled={form.isSubmitting}
      >
        Save draft
      </Button>
      <Show when={saved()}>
        <p class="text-sm text-success">Saved.</p>
      </Show>
    </form.Form>
  )
}
```

### Restore the initial snapshot

A `type="reset"` button restores `initialInput` and clears validation metadata.

```tsx
import { Button, createForm, Input } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

const schema = v.object({ name: v.pipe(v.string(), v.nonEmpty('A name is required.')) })

export function Reset() {
  const [resetCount, setResetCount] = createSignal(0)
  const form = createForm({ schema, initialInput: { name: 'Draft document' } })

  return (
    <form.Form onReset={() => setResetCount((count) => count + 1)} class="max-w-sm space-y-4">
      <form.Field name="name" label="Name">
        <Input />
      </form.Field>
      <div class="flex gap-2">
        <Button type="submit">Submit</Button>
        <Button type="reset" variant="outline">
          Reset
        </Button>
      </div>
      <p class="text-sm text-muted-foreground">Reset events: {resetCount()}</p>
    </form.Form>
  )
}
```

### Validate name and email

Schema messages surface on the bound field after submit or configured input validation.

```tsx
import { Button, createForm, Input } from 'moraine'
import { Show, createSignal } from 'solid-js'
import * as v from 'valibot'

const schema = v.object({
  email: v.pipe(v.string(), v.email('Enter a valid email address.')),
  name: v.pipe(v.string(), v.minLength(2, 'Enter at least two characters.')),
})

export function Validation() {
  const [submitted, setSubmitted] = createSignal(false)
  const form = createForm({ schema, initialInput: { email: '', name: '' } })

  return (
    <form.Form onSubmit={() => setSubmitted(true)} class="max-w-sm space-y-4">
      <form.Field name="name" label="Name" required>
        <Input placeholder="Ada Lovelace" />
      </form.Field>
      <form.Field name="email" label="Email" required>
        <Input type="email" placeholder="ada@example.com" />
      </form.Field>
      <Button type="submit">Submit</Button>
      <Show when={submitted()}>
        <p class="text-sm text-success">Form submitted.</p>
      </Show>
    </form.Form>
  )
}
```

### Show a server error on a token

Pass an application or server string to `form.Field error={...}` to force an error outside the
schema.

```tsx
import { Button, createForm, Input } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

export function ManualError() {
  const [error, setError] = createSignal<string | undefined>('Personal access token has expired.')
  const form = createForm({
    schema: v.object({ token: v.string() }),
    initialInput: { token: 'ghp_9f823a10bc47e' },
  })

  return (
    <div class="max-w-md w-full space-y-4">
      <form.Field
        name="token"
        label="Personal Access Token"
        hint="Fine-grained permissions"
        description="Required to synchronize remote repositories."
        error={error()}
        required
      >
        <Input
          type="password"
          onInput={() => {
            if (error()) {
              setError(undefined)
            }
          }}
          placeholder="Enter new token..."
        />
      </form.Field>

      <div class="flex gap-2">
        <Button
          size="sm"
          variant="soft"
          tone="neutral"
          onClick={() => setError('Invalid API token checksum. Please regenerate in settings.')}
        >
          Simulate Server Error
        </Button>
      </div>
    </div>
  )
}
```

### Change the control from field error

Give `form.Field` a child render function to read `{ error }` while the control still inherits the
bound field state.

```tsx
import { Button, createForm, Input } from 'moraine'
import * as v from 'valibot'

export function RenderContext() {
  const form = createForm({
    schema: v.object({
      releaseTitle: v.pipe(v.string(), v.nonEmpty('Release title is required.')),
    }),
    initialInput: { releaseTitle: '' },
  })

  return (
    <form.Form class="mx-auto max-w-xl w-full space-y-4">
      <form.Field name="releaseTitle" label="Release Title" required>
        {(props) => <Input placeholder={props.error ? 'Title is required' : 'v2.14.0'} />}
      </form.Field>

      <Button type="submit">Create Draft</Button>
    </form.Form>
  )
}
```

### Create a project with mixed controls

Compose `Input`, `Textarea`, `Select`, and `Checkbox` in one schema-validated form.

```tsx
import { Button, Checkbox, createForm, Input, Select, Textarea } from 'moraine'
import { Show, createSignal } from 'solid-js'
import * as v from 'valibot'

const schema = v.object({
  name: v.pipe(v.string(), v.nonEmpty('A project name is required.')),
  description: v.pipe(v.string(), v.nonEmpty('A project description is required.')),
  visibility: v.pipe(v.string(), v.nonEmpty('Please select visibility.')),
  terms: v.pipe(v.boolean(), v.literal(true, 'You must accept the terms and conditions.')),
})

export function MixedFields() {
  const [submitted, setSubmitted] = createSignal(false)
  const form = createForm({
    schema,
    initialInput: { name: '', description: '', visibility: '', terms: false },
  })

  return (
    <form.Form onSubmit={() => setSubmitted(true)} class="max-w-sm space-y-4">
      <form.Field name="name" label="Project name" required>
        <Input placeholder="Documentation refresh" />
      </form.Field>
      <form.Field name="description" label="Description" required>
        <Textarea placeholder="Project description" />
      </form.Field>
      <form.Field name="visibility" label="Visibility" required>
        <Select
          placeholder="Select visibility"
          items={[
            { label: 'Private', value: 'private' },
            { label: 'Team', value: 'team' },
          ]}
        />
      </form.Field>
      <form.Field name="terms" required>
        <Checkbox label="I accept the terms and conditions" />
      </form.Field>
      <Button type="submit">Create project</Button>
      <Show when={submitted()}>
        <p class="text-sm text-success">Project created.</p>
      </Show>
    </form.Form>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-submitting` | `form` | Present while the form is being submitted. |

### Props

#### form.Form

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| onSubmit | ((output: InferOutput<TSchema>, event: SubmitEvent) => unknown) \| undefined | — | Called when the form is submitted and the schema validates. Receives the schema output<br>(after any `valibot` transforms, not the raw input) and the native `SubmitEvent`. The native<br>submit is always prevented, and invalid submits focus the first invalid field without calling<br>this handler. `form.isSubmitting` stays `true` until a returned promise settles; a thrown<br>or rejected error is stored in the form `errors` instead of propagating. |
| translations | Translations \| undefined | — | Localized message overrides for this form instance. `unknownError` is the form error recorded when a submit handler throws an error without a `message`. |
| children | JSX.Element \| undefined | — | Content rendered inside the element. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`onSubmit` example**

```tsx
import { createForm, Button, Field, Input } from 'moraine'
import * as v from 'valibot'

const form = createForm({ schema: v.object({ email: v.pipe(v.string(), v.email()) }) })

<form.Form onSubmit={async (output) => {
  await fetch('/api/subscribe', { method: 'POST', body: JSON.stringify(output) })
}}>
  <form.Field name="email" label="Email"><Input type="email" /></form.Field>
  <Button type="submit">Subscribe</Button>
</form.Form>
```

#### form.Field

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| description | JSX.Element \| undefined | — | Description rendered under the label, above the control. It is linked to the control with<br>`aria-describedby`. |
| disabled | boolean \| undefined | — | Whether nested controls inherit a disabled state. A control's own `disabled` prop takes<br>precedence. |
| error | JSX.Element \| undefined | — | Error message rendered under the control; it replaces `help` and marks the control with<br>`aria-invalid`. When unset (`undefined` or `null`), the error of the form binding is used.<br>`false` suppresses any error, including the bound one. Empty content such as `''` or<br>`true` displays nothing. |
| help | JSX.Element \| undefined | — | Help text rendered under the control. It is hidden while an error is displayed and linked to<br>the control with `aria-describedby`. |
| hiddenLabel | string \| undefined | — | Visually hidden label used as the accessible name when `label` has no content. Ignored when<br>`label` is non-empty. |
| hint | JSX.Element \| undefined | — | Hint rendered beside the label, such as "Optional". Only shown when the field has a label<br>(visible or `hiddenLabel`). |
| id | string \| undefined | — | Prefix for the IDs of the label, hint, description, help, and error elements, which are<br>used for `aria-labelledby` and `aria-describedby`. It is not set on the root element.<br>A unique ID is generated when omitted. |
| label | JSX.Element \| undefined | — | Label for the control. Rendered as a `<label>` pointing to the nested control and used as<br>its `aria-labelledby`. Empty content (`''`, `null`, `false`) counts as no label. |
| name* | FieldName<TSchema> | — | Schema field this `Field` binds to. A string is a top-level key of the schema, and an<br>array is a path to a nested object property or array item, such as `['profile', 'name']`<br>or `['tags', 0]`. A dotted string like `'profile.name'` is read as one top-level key. |
| orientation | 'vertical' \| 'horizontal' \| undefined | 'vertical' | Visual layout direction. |
| readOnly | boolean \| undefined | — | Whether nested controls inherit a read-only state. A control's own `readOnly` prop takes<br>precedence. |
| required | boolean \| undefined | false | Whether nested controls inherit the required state (`aria-required`) and the label shows a<br>required indicator. A control's own `required` prop takes precedence. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Visual size of the component. |
| as | T \| undefined | 'div' | The HTML element or component to render as. |
| children | JSX.Element \| Component<RenderProps> \| undefined | — | Content, or a render function that receives the field state as props. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`name` example**

```tsx
import { createForm, Field, Input } from 'moraine'
import * as v from 'valibot'

const form = createForm({ schema: v.object({ profile: v.object({ name: v.string() }) }) })

<form.Form>
  <form.Field name={['profile', 'name']} label="Name"><Input /></form.Field>
</form.Form>
```
