Menhir

Form

View as Markdown

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.

Size
1.0 kB

Example

Styling

Try “menhir”, or leave it empty.

FormExample.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>
  );
}

Anatomy

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

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.

PropTypeDefaultDescription
errorsPartial<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.

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

Keyboard

KeysAction
EnterIn 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.

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.

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>
  );
}