Menhir

Forms without a library

Menhir's Field and Form hold no values. A value stays in its control and is read with FormData, or lives in your own state, where Solid already has what a form needs: a store for nested and array values, memos for checks, actions for submitting. What Menhir adds is where an error goes and when it shows. This page builds two forms that way.

A form on a store

A talk proposal with a nested value (the speaker), a list of links with rows added and removed, a field that depends on another, a schema run on submit, a pending submit button and a reset.

import {
  For,
  Show,
  action,
  createOptimistic,
  createSignal,
  createStore,
  snapshot,
} 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 { Input } from "menhir/input";

import { proposalSchema } from "./proposalSchema";
import type { Proposal } from "./proposalSchema";

const emptyProposal = (): Proposal => ({
  title: "",
  speaker: { name: "", email: "" },
  links: [""],
});

// Stands for your server.
async function sendProposal(proposal: Proposal) {
  await new Promise((resolve) => setTimeout(resolve, 500));
  return proposal.title;
}

/** A text Field whose value is in the app's state. */
function TextField(props: {
  name: string;
  label: string;
  type?: string;
  value: string;
  onValueChange: (value: string) => void;
  error?: string;
}) {
  return (
    <Field.Root name={props.name} error={props.error}>
      <Field.Label>{props.label}</Field.Label>
      <Field.Control
        type={props.type}
        render={(p) => (
          <Input.Root
            {...p}
            value={props.value}
            onValueChange={props.onValueChange}
          />
        )}
      />
      <Field.Error />
    </Field.Root>
  );
}

export default function ProposalForm() {
  const [proposal, setProposal] = createStore(emptyProposal());
  // Not part of the proposal: it only has to match the email.
  const [emailAgain, setEmailAgain] = createSignal("");
  const [errors, setErrors] = createSignal<FormErrors>({});
  const [sent, setSent] = createSignal<string>();
  // True while the action runs; it reverts once the action settles.
  const [sending, setSending] = createOptimistic(false);

  const send = action(function* (values: Proposal) {
    setSending(true);
    const title: string = yield sendProposal(values);
    setSent(title);
  });

  // A schema may answer at once or later, so its answer is awaited.
  async function validateAndSend() {
    const result = await proposalSchema["~standard"].validate(
      snapshot(proposal),
    );
    if (result.issues) {
      setErrors(issuesToErrors(result.issues));
    } else {
      setErrors({});
      send(result.value);
    }
  }

  return (
    <Form
      errors={errors()}
      onSubmit={(event) => {
        event.preventDefault();
        void validateAndSend();
      }}
      // Each Input asks for its default on a reset, which empties the
      // store's values; the rows go back to one.
      onReset={() => {
        setProposal((s) => {
          s.links.splice(1);
        });
        setErrors({});
        setSent(undefined);
      }}
    >
      <TextField
        name="title"
        label="Title"
        value={proposal.title}
        onValueChange={(value) =>
          setProposal((s) => {
            s.title = value;
          })
        }
      />
      <TextField
        name="speaker.name"
        label="Your name"
        value={proposal.speaker.name}
        onValueChange={(value) =>
          setProposal((s) => {
            s.speaker.name = value;
          })
        }
      />
      <TextField
        name="speaker.email"
        label="Email"
        type="email"
        value={proposal.speaker.email}
        onValueChange={(value) =>
          setProposal((s) => {
            s.speaker.email = value;
          })
        }
      />
      <TextField
        name="emailAgain"
        label="Email again"
        type="email"
        value={emailAgain()}
        onValueChange={setEmailAgain}
        // Depends on another field, checked as the user types, and shown
        // once this field is touched.
        error={
          emailAgain() !== proposal.speaker.email
            ? "The addresses differ."
            : undefined
        }
      />
      <fieldset>
        <legend>Recordings or slides</legend>
        {/* By index: a row keyed by its text would be made again on each edit. */}
        <For each={proposal.links} keyed={false}>
          {(link, i) => (
            <div>
              <TextField
                name={`links.${i}`}
                label={`Link ${i + 1}`}
                type="url"
                value={link()}
                onValueChange={(value) =>
                  setProposal((s) => {
                    s.links[i] = value;
                  })
                }
              />
              <button
                type="button"
                onClick={() =>
                  setProposal((s) => {
                    s.links.splice(i, 1);
                  })
                }
              >
                Remove link {i + 1}
              </button>
            </div>
          )}
        </For>
        <button
          type="button"
          onClick={() =>
            setProposal((s) => {
              s.links.push("");
            })
          }
        >
          Add a link
        </button>
      </fieldset>
      <Show when={errors()[""]}>
        {(message) => <p role="alert">{message()}</p>}
      </Show>
      <button type="submit" disabled={sending()}>
        {sending() ? "Sending…" : "Send proposal"}
      </button>
      <button type="reset">Start again</button>
      <Show when={sent()}>
        {(title) => <p role="status">Received: {title()}</p>}
      </Show>
    </Form>
  );
}
  • Values are in a store, written through the draft: s.speaker.name = value, s.links.push(""). Each control is an Input with a controlled value, in a Field.
  • Names are paths, joined with dots: speaker.name, links.0. A schema's issue for ["links", 0] reaches the Field named links.0. A list of strings is a <For keyed={false}>, by index, so a row is not made again on each edit.
  • The browser checks first. Form blocks a submission while a control is invalid, such as an email field holding no address, and focuses it. Only then does onSubmit run the schema.
  • The schema runs on submit, and issuesToErrors turns its issues into Form's errors. Each error shows in its Field at once, and hides when the user edits that control. An issue with no path, such as "add a link", is an error of the whole form, under "", which you show yourself.
  • Errors as the user types go on a Field's own error, such as the second email that must match the first. Field shows one only once the field is touched: focus has left it, or a submission was tried.
  • Pending is a createOptimistic(false) flag the action sets, which reverts once the action settles. Form holds no pending state.
  • Reset is the browser's. Each controlled Input asks for its default through onValueChange, Fields forget they were touched, Form hides its errors, and onReset takes the list back to one row.

The schema can come from any library that implements Standard Schema. issuesToErrors reads only the issues' message and path. Here the schema is written by hand:

import type { Issue } from "menhir/form/standard-schema";

export type Proposal = {
  title: string;
  speaker: { name: string; email: string };
  links: string[];
};

// Any schema library that implements Standard Schema fits here. This schema
// is written by hand, so that the example depends on none.
export const proposalSchema = {
  "~standard": {
    version: 1,
    vendor: "example",
    validate(value: Proposal) {
      const issues: Issue[] = [];
      if (!value.title.trim()) {
        issues.push({ message: "Give the talk a title.", path: ["title"] });
      }
      if (!value.speaker.name.trim()) {
        issues.push({ message: "Enter your name.", path: ["speaker", "name"] });
      }
      value.links.forEach((link, i) => {
        if (!URL.canParse(link)) {
          issues.push({
            message: "Enter a full address, with https://.",
            path: ["links", i],
          });
        }
      });
      // No path: an error of the whole form, under "".
      if (value.links.length === 0) {
        issues.push({ message: "Add a link to a recording or slides." });
      }
      return issues.length > 0 ? { issues } : { value };
    },
  },
} as const;

An uncontrolled form, with the router

The shape of the Solid 2.0 forms guide: the inputs hold their values, the browser builds the FormData, and Solid Router's formAction sends it. Form passes method and action through, and takes the errors of the router's last submission.

import { formAction, useSubmissions } from "@solidjs/router";
import { Field } from "menhir/field";
import { Form } from "menhir/form";
import type { FormErrors } from "menhir/form";

// In an app, a server function ("use server") that validates and saves,
// and answers with its errors keyed by name.
const subscribe = formAction(async (form: FormData) => {
  await new Promise((resolve) => setTimeout(resolve, 500));
  if (form.get("email") === "ada@example.com") {
    throw { errors: { email: "This address is subscribed already." } };
  }
});

export default function SubscribeForm() {
  const submissions = useSubmissions(subscribe);
  // The errors of the last submission, also after one made before the
  // page hydrated, which the server renders.
  const errors = (): FormErrors => submissions.at(-1)?.error?.errors ?? {};
  return (
    // The router sets aria-busy while it submits: style form[aria-busy].
    <Form method="post" action={subscribe} errors={errors()}>
      <Field.Root name="email">
        <Field.Label>Email</Field.Label>
        <Field.Control type="email" required />
        <Field.Error />
      </Field.Root>
      <button type="submit">Subscribe</button>
    </Form>
  );
}
  • A blocked submission is cancelled before the router sees it, so the action runs only for a valid form.
  • The router sets aria-busy on the form while it submits: style form[aria-busy] button.
  • Before the page hydrates, the form is a plain post. The server HTML has no novalidate, so the browser checks the controls itself, and the errors the server returns are rendered in their Fields.

Next

See Form and Field for every prop.