# Form

> A form wrapper that replaces native validation bubbles with an error summary, linked to each invalid field and its inline message.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/form`
- File: `src/components/haze/ui/form.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/utils
- Docs page: https://hazeui.com/ui/form

## Use when
- A signup, invite or settings form with several required fields
- You want every error listed at the top with a link to the field, plus a message under it
- Native browser validation should still work if the script does not run

## Avoid when
- A single field with one error line. Use field.
- You only need to group related controls under a legend. Use fieldset.
- A one-input search or newsletter box. Use input-group.

## Alternatives
- [field](https://hazeui.com/ui/field.md)
- [fieldset](https://hazeui.com/ui/fieldset.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Form id. The summary id derives from it. |
| action | `string` |  | no | Where the form posts. |
| method | `"get" \| "post" \| "dialog"` |  | no | Form method. |
| novalidate | `boolean` | false | no | Turns native bubbles off in the markup. The script does it anyway. |
| summaryTitle | `string` | "Fix {count} problems to continue" | no | Summary title for two or more problems; {count} becomes the number. |
| summaryTitleOne | `string` | "Fix 1 problem to continue" | no | Summary title for exactly one problem. |
| submitLabel | `string` |  | no | Adds a built-in submit button with this label. |
| fallbackLabel | `string` | "This field" | no | Name used in the summary when a control has no label. |
| class | `string` |  | no | Extra classes on the form. |
| default slot | `slot` |  | yes | Fields: field, checkbox and similar controls. |
| actions | `slot` |  | no | Buttons placed after the built-in submit button. |

## Accessibility
- On a failed submit the summary panel (role alert) takes focus and lists each problem as a link to its field.
- Every invalid control gets aria-invalid and an inline message linked through aria-describedby; the message has an icon and text, never color alone.
- Add data-error="…" to a control to replace the browser's wording in both the summary and the inline message.
- Fields are rechecked on blur after the first attempt, and on input while invalid. The summary updates only when the set of invalid fields changes, so a screen reader is not interrupted on every keystroke.
- Without script the browser's own validation bubbles still block an incomplete submit.
- Key Tab: After a failed submit, move from the summary through its links to the fields.
- Key Enter on a summary link: Move focus to that field.

## Agent prompts

### Install and use

Install the Haze UI component "Form" with `npx shadcn@latest add @haze/form`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Form from "@/components/haze/ui/form.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/form.md

### Customize with real content

Adapt the Haze form ui for our product. Replace the demo values of these props with our real content: id, action, method, novalidate, summaryTitle, summaryTitleOne, submitLabel, fallbackLabel, class, default slot, actions. Keep the layout, the heading level rules and these accessibility details: On a failed submit the summary panel (role alert) takes focus and lists each problem as a link to its field. Every invalid control gets aria-invalid and an inline message linked through aria-describedby; the message has an icon and text, never color alone. Add data-error="…" to a control to replace the browser's wording in both the summary and the inline message. Fields are rechecked on blur after the first attempt, and on input while invalid. The summary updates only when the set of invalid fields changes, so a screen reader is not interrupted on every keystroke. Without script the browser's own validation bubbles still block an incomplete submit. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using form, check it fits: use it when a signup, invite or settings form with several required fields; you want every error listed at the top with a link to the field, plus a message under it; native browser validation should still work if the script does not run. Avoid it when a single field with one error line. use field.; you only need to group related controls under a legend. use fieldset.; a one-input search or newsletter box. use input-group.. Alternatives: @haze/field, @haze/fieldset.

## Example requests that should lead here
- Build an invite form with name, email, role and a consent checkbox that lists errors at the top.
- Wrap my checkout fields in a form that shows an error summary and marks each invalid field.

## Source

```astro
---
import { CircleAlert } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

interface Props {
  /** Required. The summary panel and its parts derive their ids from it. */
  id: string;
  action?: string;
  method?: "get" | "post" | "dialog";
  /** Turns native validation bubbles off in the markup. The script always does this for you and shows the summary instead. */
  novalidate?: boolean;
  /** Summary title for two or more problems. `{count}` is replaced with the number. */
  summaryTitle?: string;
  /** Summary title for exactly one problem. */
  summaryTitleOne?: string;
  /** Label of the built-in submit button. Leave empty to supply your own actions in the `actions` slot. */
  submitLabel?: string;
  /** Used in the summary when a control has no label text. */
  fallbackLabel?: string;
  class?: string;
  /** Any other form attribute, for example enctype, autocomplete or aria-label. */
  [key: string]: unknown;
}

const {
  id,
  action,
  method,
  novalidate = false,
  summaryTitle = "Fix {count} problems to continue",
  summaryTitleOne = "Fix 1 problem to continue",
  submitLabel,
  fallbackLabel = "This field",
  class: className,
  ...rest
} = Astro.props;
const hasActions = Astro.slots.has("actions");
---

<form
  id={id}
  action={action}
  method={method}
  novalidate={novalidate}
  data-haze-form
  data-title-many={summaryTitle}
  data-title-one={summaryTitleOne}
  data-fallback-label={fallbackLabel}
  class={cn("grid gap-5", className)}
  {...rest}
>
  <div
    id={`${id}-summary`}
    data-form-summary
    hidden
    role="alert"
    tabindex="-1"
    class="grid grid-cols-[auto_1fr] items-start gap-x-3 rounded-xl border border-destructive-border bg-destructive/8 p-4 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
  >
    <CircleAlert class="mt-0.5 size-4.5 shrink-0 text-destructive" aria-hidden="true" />
    <div class="min-w-0">
      <p data-form-summary-title class="text-[0.8125rem]/5 font-medium tracking-[-0.01em] text-foreground"></p>
      <ul data-form-summary-list class="mt-2 grid gap-1.5 text-[0.8125rem]/5 text-foreground"></ul>
    </div>
  </div>
  <slot />
  {
    (submitLabel || hasActions) && (
      <div class="flex flex-wrap items-center gap-3">
        {submitLabel && <Button type="submit">{submitLabel}</Button>}
        <slot name="actions" />
      </div>
    )
  }
  <template data-form-error>
    <p class="flex items-start gap-1.5 text-xs/5 text-destructive">
      <CircleAlert class="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
      <span data-form-error-text></span>
    </p>
  </template>
</form>

<script>
  type Control = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;

  function enhance(form: HTMLFormElement) {
    if (form.hasAttribute("data-enhanced")) return;
    form.setAttribute("data-enhanced", "");
    form.noValidate = true;
    const summary = form.querySelector<HTMLElement>("[data-form-summary]");
    const titleEl = form.querySelector<HTMLElement>("[data-form-summary-title]");
    const listEl = form.querySelector<HTMLElement>("[data-form-summary-list]");
    const template = form.querySelector<HTMLTemplateElement>("template[data-form-error]");
    if (!summary || !titleEl || !listEl || !template) return;
    const titleMany = form.getAttribute("data-title-many") ?? "Fix {count} problems to continue";
    const titleOne = form.getAttribute("data-title-one") ?? "Fix 1 problem to continue";
    const fallback = form.getAttribute("data-fallback-label") ?? "This field";
    let attempted = false;
    let shownKey = "";

    const controls = (): Control[] => {
      const seen = new Set<string>();
      const result: Control[] = [];
      for (const el of Array.from(form.elements)) {
        if (!(el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement)) continue;
        if (!el.willValidate || !el.id || el.type === "hidden" || el.type === "submit" || el.type === "button" || el.type === "reset") continue;
        if (el instanceof HTMLInputElement && el.type === "radio") {
          if (seen.has(el.name)) continue;
          seen.add(el.name);
        }
        result.push(el);
      }
      return result;
    };
    const labelOf = (el: Control) => {
      const label = form.querySelector<HTMLElement>(`label[for="${CSS.escape(el.id)}"]`) ?? el.labels?.[0];
      if (label) {
        const copy = label.cloneNode(true) as HTMLElement;
        copy.querySelectorAll("[aria-hidden='true'], .sr-only").forEach((n) => n.remove());
        const text = copy.textContent?.replace(/\s+/g, " ").trim();
        if (text) return text;
      }
      return el.getAttribute("aria-label") || fallback;
    };
    const messageOf = (el: Control) => el.getAttribute("data-error") || el.validationMessage;

    const setError = (el: Control, message: string | null) => {
      const errorId = `${el.id}-error`;
      let node = document.getElementById(errorId);
      const tokens = (el.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean);
      if (message === null) {
        node?.remove();
        el.removeAttribute("aria-invalid");
        const rest = tokens.filter((t) => t !== errorId);
        if (rest.length) el.setAttribute("aria-describedby", rest.join(" "));
        else el.removeAttribute("aria-describedby");
        return;
      }
      if (!node) {
        node = (template.content.firstElementChild as HTMLElement).cloneNode(true) as HTMLElement;
        node.id = errorId;
        const label = form.querySelector<HTMLElement>(`label[for="${CSS.escape(el.id)}"]`);
        const host = label?.parentElement && label.parentElement !== form ? label.parentElement : el.parentElement;
        if (host && host !== form) host.append(node);
        else {
          const wrap = el.closest("label");
          (wrap && form.contains(wrap) ? wrap : el).after(node);
        }
      }
      const text = node.querySelector("[data-form-error-text]") ?? node.querySelector("span:last-child");
      if (text && text.textContent !== message) text.textContent = message;
      el.setAttribute("aria-invalid", "true");
      if (!tokens.includes(errorId)) el.setAttribute("aria-describedby", [...tokens, errorId].join(" "));
    };
    const check = (el: Control) => setError(el, el.checkValidity() ? null : messageOf(el));

    const renderSummary = (force: boolean) => {
      const bad = controls().filter((el) => el.getAttribute("aria-invalid") === "true");
      if (bad.length === 0) {
        summary.hidden = true;
        listEl.replaceChildren();
        shownKey = "";
        return;
      }
      const key = bad.map((el) => `${el.id}:${messageOf(el)}`).join("|");
      if (!force && key === shownKey && !summary.hidden) return;
      shownKey = key;
      const title = bad.length === 1 ? titleOne : titleMany.replace("{count}", String(bad.length));
      if (titleEl.textContent !== title) titleEl.textContent = title;
      listEl.replaceChildren(
        ...bad.map((el) => {
          const item = document.createElement("li");
          const link = document.createElement("a");
          link.href = `#${el.id}`;
          link.className =
            "rounded-xs underline decoration-muted-foreground underline-offset-4 hover:decoration-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring";
          link.textContent = `${labelOf(el)}: ${messageOf(el)}`;
          link.addEventListener("click", (event) => {
            event.preventDefault();
            el.focus();
            el.scrollIntoView({ block: "center", behavior: "auto" });
          });
          item.append(link);
          return item;
        }),
      );
      summary.hidden = false;
    };

    form.addEventListener("submit", (event) => {
      if ((event.submitter as HTMLElement | null)?.hasAttribute("formnovalidate")) return;
      attempted = true;
      controls().forEach(check);
      const hasErrors = controls().some((el) => el.getAttribute("aria-invalid") === "true");
      renderSummary(true);
      if (hasErrors) {
        event.preventDefault();
        summary.focus();
      }
    });
    form.addEventListener("focusout", (event) => {
      const el = event.target as Control;
      if (!attempted || !controls().includes(el)) return;
      check(el);
      renderSummary(false);
    });
    const live = (event: Event) => {
      const el = event.target as Control;
      if (!attempted || el.getAttribute?.("aria-invalid") !== "true") return;
      check(el);
      renderSummary(false);
    };
    form.addEventListener("input", live);
    form.addEventListener("change", live);
    form.addEventListener("reset", () => {
      attempted = false;
      controls().forEach((el) => setError(el, null));
      renderSummary(true);
    });
  }
  const init = () => document.querySelectorAll<HTMLFormElement>("form[data-haze-form]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-form-listener")) {
    document.documentElement.setAttribute("data-haze-form-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
