# Form

A form that shows errors in its Fields and blocks a submission while a control is invalid. It renders a native <form>, so a router's form action and a submission made before the page hydrates work as on any form. Errors from a server or a schema go in as errors, keyed by each Field's name, and show at once. A blocked submission focuses the first invalid control and shows every Field's error in place of the browser's bubble. Form holds no values: they stay in the controls, read with FormData, or in your own state.

- Entry point: `menhir/form`
- Size: 1.0 kB, minified and gzipped, Solid left out

> To add Form to a project, install the packages below with the project's package manager, then copy the example that matches how the project is styled, Tailwind CSS or plain CSS, and adapt its markup and class names to the project.

## Install

```sh
pnpm add menhir solid-js @solidjs/web
```

## Anatomy

```tsx
<Form>
  <Field.Root name="email">…</Field.Root>
</Form>
```

## Example

### Tailwind CSS

`FormExample.tsx`:

```tsx
import { createSignal } from "solid-js";
import { Field } from "menhir/field";
import { Form } from "menhir/form";
import type { FormErrors } from "menhir/form";

export default function FormExample() {
  const [errors, setErrors] = createSignal<FormErrors>({});
  return (
    <Form
      class="flex flex-col items-start gap-4"
      errors={errors()}
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        // As a server would answer: the name is taken.
        setErrors(
          data.get("username") === "menhir"
            ? { username: "That name is taken." }
            : {},
        );
      }}
    >
      <Field.Root name="username" class="flex flex-col gap-1">
        <Field.Label class="text-sm font-medium">Username</Field.Label>
        <Field.Control
          required
          class="rounded-md border border-stone-300 px-3 py-1.5 data-invalid:border-red-600 dark:border-stone-700 dark:data-invalid:border-red-400"
        />
        <Field.Description class="text-sm text-stone-500 dark:text-stone-400">
          Try “menhir”, or leave it empty.
        </Field.Description>
        <Field.Error class="text-sm text-red-600 dark:text-red-400" />
      </Field.Root>
      <button
        type="submit"
        class="rounded-md bg-stone-800 px-3 py-1.5 text-sm font-medium text-white dark:bg-stone-300 dark:text-stone-900"
      >
        Join
      </button>
    </Form>
  );
}
```

### CSS

`FormExample.tsx`:

```tsx
import { createSignal } from "solid-js";
import { Field } from "menhir/field";
import { Form } from "menhir/form";
import type { FormErrors } from "menhir/form";

import "./form.css";

export default function FormExample() {
  const [errors, setErrors] = createSignal<FormErrors>({});
  return (
    <Form
      class="form-example"
      errors={errors()}
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        // As a server would answer: the name is taken.
        setErrors(
          data.get("username") === "menhir"
            ? { username: "That name is taken." }
            : {},
        );
      }}
    >
      <Field.Root name="username" class="field">
        <Field.Label>Username</Field.Label>
        <Field.Control required class="control" />
        <Field.Description class="description">
          Try “menhir”, or leave it empty.
        </Field.Description>
        <Field.Error class="error" />
      </Field.Root>
      <button type="submit">Join</button>
    </Form>
  );
}
```

`form.css`:

```css
/* The least CSS that shows a Form's errors: the label above the input,
   and the input and the error in red while the field shows an error
   (data-invalid: once the field was touched, or at once for an error the
   Form hands it). Everything else is the browser's. Colours are Tailwind's
   stone and red palettes; light-dark() picks the second one in dark mode
   (color-scheme: dark). */
.form-example {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 1rem;
  font-family: system-ui, sans-serif;
}

.field {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.description {
  margin: 0;
  font-size: 0.875rem;
  color: light-dark(
    oklch(55.3% 0.013 58.071) /* stone-500 */,
    oklch(70.9% 0.01 56.259) /* stone-400 */
  );
}

.control[data-invalid] {
  outline: 2px solid
    light-dark(
      oklch(57.7% 0.245 27.325) /* red-600 */,
      oklch(70.4% 0.191 22.216) /* red-400 */
    );
}

.error {
  margin: 0;
  font-size: 0.875rem;
  color: light-dark(
    oklch(57.7% 0.245 27.325) /* red-600 */,
    oklch(70.4% 0.191 22.216) /* red-400 */
  );
}
```

## API reference

### Form

The form: a <form> that takes every attribute of one, such as method, action or aria-busy. Once hydrated it has novalidate, so the Fields show the errors instead of the browser's bubble; before, the browser validates a submission itself.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `errors` | `Partial<Record<string, string>>` | — | Errors keyed by a Field's name, one message each, such as a server's answer or a schema's issues. A nested or repeated value's key is its path joined with dots: "address.city", "links.0". Each shows in its Field at once, and hides once its control is edited or the form is reset, until you pass a new object. They never block a submission. |
| `onSubmit` | `(event: SubmitEvent) => void` | — | The form's submit event, called only when no control is invalid. Form does not cancel it: call event.preventDefault() to submit in the page, such as through an action, or leave it for a router's form action or the server. |
| `render` | `(props) => JSX.Element` | — | Renders the form as another element or component that spreads its props onto a <form>. Read once. |

### issuesToErrors

A function, in menhir/form/standard-schema, that turns a schema's issues into errors: each message under its path joined with dots, the first issue on a path winning, and an issue with no path under "", for you to show above the submit button. It reads the Standard Schema issue (message and path), so it works with any schema library that implements it, and depends on none. A Form without a schema does not bundle it.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `issues` | `ReadonlyArray<{ message: string; path?: ReadonlyArray<PropertyKey \| { key: PropertyKey }> }>` | — | The issues of a failed validation, such as result.issues of schema["~standard"].validate(value). |

## Keyboard

| Keys | Action |
| --- | --- |
| `Enter` | In a text input, submits the form, as the browser does. A blocked submission moves focus to the first invalid control, which names its error. |

## Validated by a schema on submit

Run the schema in onSubmit, once the browser's own checks have passed, and pass its issues through issuesToErrors. Each error shows in the Field of that name, and hides once the user edits that control. For errors shown as the user types, once a field is touched, put the result of a memo on the Field's own error instead.

`FormWithSchema.tsx`:

```tsx
import { createSignal } from "solid-js";
import { Field } from "menhir/field";
import { Form } from "menhir/form";
import type { FormErrors } from "menhir/form";
import { issuesToErrors } from "menhir/form/standard-schema";
import type { Issue } from "menhir/form/standard-schema";

type SignUp = { email: string; password: string; confirm: string };

// Any schema library that implements Standard Schema fits here. This schema
// is written by hand, so that the example depends on none.
const signUpSchema = {
  "~standard": {
    version: 1,
    vendor: "example",
    validate(value: SignUp) {
      const issues: Issue[] = [];
      if (value.password.length < 8) {
        issues.push({
          message: "Use 8 characters or more.",
          path: ["password"],
        });
      }
      if (value.confirm !== value.password) {
        issues.push({ message: "The passwords differ.", path: ["confirm"] });
      }
      return issues.length > 0 ? { issues } : { value };
    },
  },
} as const;

export default function FormWithSchema() {
  const [errors, setErrors] = createSignal<FormErrors>({});
  // A schema may answer at once or later, so its answer is awaited.
  async function validate(values: SignUp) {
    const result = await signUpSchema["~standard"].validate(values);
    setErrors(result.issues ? issuesToErrors(result.issues) : {});
    if (!result.issues) {
      // Send result.value to your server.
    }
  }
  return (
    <Form
      errors={errors()}
      onSubmit={(event) => {
        event.preventDefault();
        void validate(
          Object.fromEntries(new FormData(event.currentTarget)) as SignUp,
        );
      }}
    >
      <Field.Root name="email">
        <Field.Label>Email</Field.Label>
        <Field.Control type="email" required />
        <Field.Error />
      </Field.Root>
      <Field.Root name="password">
        <Field.Label>Password</Field.Label>
        <Field.Control type="password" required />
        <Field.Error />
      </Field.Root>
      <Field.Root name="confirm">
        <Field.Label>Password again</Field.Label>
        <Field.Control type="password" required />
        <Field.Error />
      </Field.Root>
      <button type="submit">Sign up</button>
    </Form>
  );
}
```

## Errors from a server

Pass the server's answer as errors. Here an action sends the form and sets a pending flag, which reverts once the action settles. With Solid Router, give the form method="post" and action={formAction(fn)}, pass the errors of its last submission as errors, and style form[aria-busy], which the router sets while it submits. A submission made before the page hydrates is posted to the server, and the errors it returns are in the server HTML, in their Fields.

`FormServerErrors.tsx`:

```tsx
import { action, createOptimistic, createSignal } from "solid-js";
import { Field } from "menhir/field";
import { Form } from "menhir/form";
import type { FormErrors } from "menhir/form";

// Stands for your server, which answers with its errors keyed by name.
async function subscribe(data: FormData): Promise<FormErrors> {
  await new Promise((resolve) => setTimeout(resolve, 500));
  return data.get("email") === "ada@example.com"
    ? { email: "This address is subscribed already." }
    : {};
}

export default function FormServerErrors() {
  const [errors, setErrors] = createSignal<FormErrors>({});
  // True while the action runs; it reverts once the action settles.
  const [sending, setSending] = createOptimistic(false);
  const send = action(function* (data: FormData) {
    setSending(true);
    const answer: FormErrors = yield subscribe(data);
    setErrors(answer);
  });
  return (
    <Form
      errors={errors()}
      aria-busy={sending() ? "true" : undefined}
      onSubmit={(event) => {
        event.preventDefault();
        send(new FormData(event.currentTarget));
      }}
    >
      <Field.Root name="email">
        <Field.Label>Email</Field.Label>
        <Field.Control type="email" required />
        <Field.Description>Try ada@example.com.</Field.Description>
        <Field.Error />
      </Field.Root>
      <button type="submit">{sending() ? "Subscribing…" : "Subscribe"}</button>
    </Form>
  );
}
```
