# Sign-up form

> Field checks, a cross-field check, a debounced server check and server errors, built with both libraries.

Source: https://forms.lunarhue.dev/react/compared/signup

Here is a sign-up form built twice: once with `@lunarhue/forms` and once with [TanStack Form](https://tanstack.com/form). Both versions render identical markup and talk to the same mock API, so the only difference is the form wiring. Toggle between the two builds in the preview below; they behave the same.

| Build (gzip) | @lunarhue/forms is | @lunarhue/forms 0.2.0 | TanStack Form 1.33.5 |
| --- | --- | --- | --- |
| Forms + app | 5.2 kB smaller (27%) | 13.8 kB | 19.0 kB |
| Total | 4.9 kB smaller (6%) | 81.3 kB | 86.2 kB |
| App only | 382 B smaller (19%) | 1.6 kB | 2.0 kB |

```tsx title="lunarhue/App.tsx"
import { createForms, debounced, fieldValidators, formValidator, pipe, useForm } from "@lunarhue/forms-react";
import { isUsernameTaken, signUp } from "../../shared/server.ts";
import { Page } from "../../shared/ui.tsx";
import { Checkbox, TextField } from "./fields.tsx";

const forms = createForms({ fields: { TextField, Checkbox } });

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Validators first run on blur and then on every input, which is the
// default, so nothing here sets it.
const signUpForm = forms.define({
  defaultValues: { email: "", username: "", password: "", confirm: "", terms: false },
  validate: {
    fields: fieldValidators({
      email: (email) => (emailPattern.test(email) ? undefined : { message: "Enter a valid email." }),
      // The sync rules answer at once. Only a well-formed name waits for a
      // pause and goes to the server. A newer run aborts the older request.
      username: pipe(
        (name) => (name.length < 3 ? { message: "Use at least 3 characters." } : undefined),
        (name) => (/^[a-z0-9_]+$/i.test(name) ? undefined : { message: "Use letters, digits and underscores." }),
        debounced(async (name, { signal }) => ((await isUsernameTaken(name, signal)) ? { message: "That username is taken." } : undefined), 400),
      ),
      password: (password) => (password.length >= 8 ? undefined : { message: "Use at least 8 characters." }),
      terms: (accepted) => (accepted ? undefined : { message: "Accept the terms to continue." }),
    }),
    // Sees the whole value, so it runs again when either password changes.
    form: formValidator(({ password, confirm }) => {
      if (confirm === "") return { fields: { confirm: { message: "Confirm your password." } } };
      if (confirm !== password) return { fields: { confirm: { message: "The passwords don't match." } } };
      return undefined;
    }),
  },
  onSubmit: async (value, { store }) => {
    const response = await signUp(value);
    if (!response.ok) {
      // Each message lands on its field and clears when the user edits it.
      store.setErrors({ fields: Object.fromEntries(Object.entries(response.errors).map(([name, message]) => [name, { message }])) });
      return undefined;
    }
    return `Welcome, ${value.username}.`;
  },
});

export function App() {
  const form = useForm(signUpForm);
  return (
    <Page title="Create an account" lede="Core only: field validators, a cross-field check, an async check and server errors.">
      <form {...form.formProps}>
        <form.TextField name="email" label="Email" type="email" />
        <form.TextField name="username" label="Username" />
        <form.TextField name="password" label="Password" type="password" />
        <form.TextField name="confirm" label="Confirm password" type="password" />
        <form.Checkbox name="terms" label="I accept the terms" />
        <form.State select={(state) => state.submitting}>
          {(submitting) => (
            <div className="actions">
              <button type="submit" disabled={submitting}>
                {submitting ? "Creating account..." : "Create account"}
              </button>
            </div>
          )}
        </form.State>
        <form.State select={(state) => state.submission}>
          {(submission) => <p role="status">{submission.status === "succeeded" ? submission.result : null}</p>}
        </form.State>
      </form>
    </Page>
  );
}
```

```tsx title="lunarhue/fields.tsx"
import { checkboxProps, type FieldApi, inputProps, type TextInputType } from "@lunarhue/forms-react";
import { CheckShell, FieldShell } from "../../shared/ui.tsx";

interface TextFieldProps {
  readonly field: FieldApi<string>;
  readonly label: string;
  readonly type?: TextInputType;
}

export function TextField({ field, label, type = "text" }: TextFieldProps) {
  return (
    <FieldShell
      id={field.id}
      errorId={field.errorId}
      label={label}
      errors={field.shownErrors.map((error) => error.message)}
      checking={field.validating}
    >
      <input {...inputProps(field, { type })} />
    </FieldShell>
  );
}

interface CheckboxProps {
  readonly field: FieldApi<boolean>;
  readonly label: string;
}

export function Checkbox({ field, label }: CheckboxProps) {
  return (
    <CheckShell errorId={field.errorId} errors={field.shownErrors.map((error) => error.message)}>
      <input {...checkboxProps(field)} />
      {label}
    </CheckShell>
  );
}
```

```tsx title="tanstack/App.tsx"
import { useState } from "react";
import { isUsernameTaken, signUp } from "../../shared/server.ts";
import { Page } from "../../shared/ui.tsx";
import { useAppForm } from "./form.tsx";

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Each check runs on every change and on blur (see useBlur in form.tsx).
// The field components show errors only once the field is blurred.
function checkEmail({ value }: { value: string }) {
  return emailPattern.test(value) ? undefined : "Enter a valid email.";
}

function checkUsername({ value }: { value: string }) {
  if (value.length < 3) return "Use at least 3 characters.";
  if (!/^[a-z0-9_]+$/i.test(value)) return "Use letters, digits and underscores.";
  return undefined;
}

async function checkUsernameFree({ value, signal }: { value: string; signal: AbortSignal }) {
  return (await isUsernameTaken(value, signal)) ? "That username is taken." : undefined;
}

function checkPassword({ value }: { value: string }) {
  return value.length >= 8 ? undefined : "Use at least 8 characters.";
}

function checkTerms({ value }: { value: boolean }) {
  return value ? undefined : "Accept the terms to continue.";
}

export function App() {
  const [welcome, setWelcome] = useState("");
  const form = useAppForm({
    defaultValues: { email: "", username: "", password: "", confirm: "", terms: false },
    validators: {
      // The request runs as a submit validator, so a refusal puts its
      // messages on the fields and onSubmit doesn't run.
      onSubmitAsync: async ({ value }) => {
        const response = await signUp(value);
        return response.ok ? undefined : { fields: response.errors };
      },
    },
    onSubmit: ({ value }) => setWelcome(`Welcome, ${value.username}.`),
  });

  return (
    <Page title="Create an account" lede="Core only: field validators, a cross-field check, an async check and server errors.">
      <form
        noValidate
        onSubmit={(event) => {
          event.preventDefault();
          void form.handleSubmit();
        }}
      >
        <form.AppField name="email" validators={{ onChange: checkEmail }}>
          {(field) => <field.TextField label="Email" type="email" />}
        </form.AppField>
        <form.AppField
          name="username"
          validators={{
            onChange: checkUsername,
            // Runs only when the sync check passes. Waits for a pause in
            // typing, and asks the server only after the first blur, since
            // nothing shows before it.
            onChangeAsyncDebounceMs: 400,
            onChangeAsync: async (props) => (props.fieldApi.state.meta.isBlurred ? checkUsernameFree(props) : undefined),
          }}
        >
          {(field) => <field.TextField label="Username" />}
        </form.AppField>
        <form.AppField name="password" validators={{ onChange: checkPassword }}>
          {(field) => <field.TextField label="Password" type="password" />}
        </form.AppField>
        <form.AppField
          name="confirm"
          validators={{
            // Runs again when the password changes.
            onChangeListenTo: ["password"],
            onChange: ({ value, fieldApi }) => checkConfirm(value, fieldApi.form.getFieldValue("password")),
          }}
        >
          {(field) => <field.TextField label="Confirm password" type="password" />}
        </form.AppField>
        <form.AppField name="terms" validators={{ onChange: checkTerms }}>
          {(field) => <field.Checkbox label="I accept the terms" />}
        </form.AppField>
        <form.AppForm>
          <form.SubmitButton label="Create account" busyLabel="Creating account..." />
        </form.AppForm>
        <p role="status">{welcome}</p>
      </form>
    </Page>
  );
}

function checkConfirm(confirm: string, password: string) {
  if (confirm === "") return "Confirm your password.";
  if (confirm !== password) return "The passwords don't match.";
  return undefined;
}
```

```tsx title="tanstack/form.tsx"
// The app's form hook. TanStack Form registers field components through
// createFormHook, and each component reads its field from context.
import { createFormHook, createFormHookContexts, useStore } from "@tanstack/react-form";
import { useId } from "react";
import { CheckShell, FieldShell } from "../../shared/ui.tsx";

const { fieldContext, formContext, useFieldContext, useFormContext } = createFormHookContexts();

/**
 * The messages to show: none until the field is blurred or the form
 * submitted. TanStack sets `isTouched` on the first keystroke, so this reads
 * `isBlurred` to wait for the blur.
 */
function useShownErrors(): string[] {
  const field = useFieldContext<unknown>();
  const submitted = useStore(field.form.store, (state) => state.submissionAttempts > 0);
  const { isBlurred, errors } = field.state.meta;
  if (!isBlurred && !submitted) return [];
  return errors.filter((error): error is string => typeof error === "string");
}

interface TextFieldProps {
  readonly label: string;
  readonly type?: "text" | "email" | "password";
}

/**
 * Marks the field blurred and runs its change validators. The forms list
 * their checks under `onChange` only: an `onBlur` error would stay until the
 * next blur, even after the user fixed the value.
 */
function useBlur() {
  const field = useFieldContext<unknown>();
  return () => {
    field.handleBlur();
    void field.validate("change");
  };
}

function TextField({ label, type = "text" }: TextFieldProps) {
  const field = useFieldContext<string>();
  const id = useId();
  const errorId = `${id}-errors`;
  const errors = useShownErrors();
  const onBlur = useBlur();
  return (
    <FieldShell
      id={id}
      errorId={errorId}
      label={label}
      errors={errors}
      checking={field.state.meta.isValidating}
    >
      <input
        id={id}
        name={field.name}
        type={type}
        value={field.state.value}
        onChange={(event) => field.handleChange(event.target.value)}
        onBlur={onBlur}
        aria-invalid={errors.length > 0 ? true : undefined}
        aria-describedby={errors.length > 0 ? errorId : undefined}
      />
    </FieldShell>
  );
}

function Checkbox({ label }: { readonly label: string }) {
  const field = useFieldContext<boolean>();
  const errorId = `${useId()}-errors`;
  const errors = useShownErrors();
  const onBlur = useBlur();
  return (
    <CheckShell errorId={errorId} errors={errors}>
      <input
        type="checkbox"
        name={field.name}
        checked={field.state.value}
        onChange={(event) => field.handleChange(event.target.checked)}
        onBlur={onBlur}
        aria-invalid={errors.length > 0 ? true : undefined}
        aria-describedby={errors.length > 0 ? errorId : undefined}
      />
      {label}
    </CheckShell>
  );
}

/**
 * TanStack ignores a submit while a check is pending, a debounce included,
 * so the button follows `canSubmit` and stays disabled until checks settle.
 * That also disables it while a touched form is invalid.
 */
function SubmitButton({ label, busyLabel }: { readonly label: string; readonly busyLabel: string }) {
  const form = useFormContext();
  return (
    <form.Subscribe selector={(state) => [state.canSubmit, state.isSubmitting] as const}>
      {([canSubmit, submitting]) => (
        <div className="actions">
          <button type="submit" disabled={!canSubmit}>
            {submitting ? busyLabel : label}
          </button>
        </div>
      )}
    </form.Subscribe>
  );
}

export const { useAppForm } = createFormHook({
  fieldContext,
  formContext,
  fieldComponents: { TextField, Checkbox },
  formComponents: { SubmitButton },
});
```

## What the form does

It collects an email, username, password, confirmation, and terms checkbox. Fields show errors after their first blur and re-validate on every keystroke after that. Password confirmation validates against `password`, re-checking automatically whenever `password` changes.

Username validation runs cheap local rules (length and allowed characters) as you type, and only hits the server once the format is valid, after a 400 ms pause, aborting stale requests if you keep typing. Try `ada` or `admin` to see the server check, or `taken@example.com` to see a server-side refusal on submit that clears as soon as you edit the email.

## Where the two implementations differ

On the `@lunarhue/forms` side, everything uses just the core package with no plugins needed. Field rules live in `validate.fields`, the password match lives in `validate.form`, and server refusals go onto fields via `setErrors`. The username check is a single `pipe` combining two sync checks with a `debounced` async check: when a sync check fails, the pipe stops and never starts the timer or request. Blur-then-input validation is the default, so no timing configuration is needed.

On the TanStack Form side, the form uses `createFormHook` for field components, per-field validators, `onChangeListenTo` to re-check password confirmation, and a form-level `onSubmitAsync` for the server call. Matching the same behavior required a few workarounds:

- TanStack keeps `onBlur` errors stuck until the next blur even after the user fixes the value, so all rules move to `onChange` and field components manually call `field.validate("change")` on blur.
- `isTouched` flips to `true` on the first keystroke, so components wait for `isBlurred` before displaying errors.
- `onChangeAsync` runs on every change, so the username validator bails out early until the field has been blurred.
- The server request runs inside `onSubmitAsync` (the documented way to attach server errors to fields), and because submit doesn't store a return value, the welcome message lives in separate React state.

You will notice one small difference in the preview: TanStack's submit ignores clicks while an async check or debounce is pending, so its button disables via `canSubmit`. Ours stays enabled and waits for any pending check to settle before submitting.

## How bundle sizes were measured

[`scripts/size-compare.ts`](https://github.com/LunarHUE/forms/blob/main/scripts/size-compare.ts) builds each app for production with Vite (minified, JavaScript only, since both share the same CSS) in three variants per library:

- **Forms + app**: the form library plus the app's own form code (excluding React, `react-dom`, and Zod).
- **Total**: everything the page loads, including React and Zod.
- **App only**: just the form-specific app code, excluding the form libraries too.

Our packages are measured from their built dist outputs, compared against TanStack Form 1.33.5. CI re-runs this script on every PR and fails if the committed numbers drift. Both apps and their shared Playwright test suite live in [`examples/compare`](https://github.com/LunarHUE/forms/tree/main/examples/compare).
