# Forms

Build forms with server actions and the field helpers.

Source: https://webjs.dev/ui/docs/forms

In this guide, we will take a look at building forms with WebJs, using a server action bound to a `<form>`. We'll cover building forms, validation, pending states, accessibility, and more.

A WebJs form is a `'use server'` action bound with `<form action=${importedAction}>`, rendered with the [Field](https://webjs.dev/ui/docs/components/field) helpers. The same form works with JavaScript off.

## Demo

We are going to build the following form with a simple text input and a textarea. On submit, a server action validates the form data, and the page re-renders with the errors when it is invalid.

```ts
import { html, nothing } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import {
  fieldGroupClass, fieldClass, fieldLabelClass, fieldDescriptionClass, fieldErrorClass,
} from '#components/ui/field.ts';
import { inputClass } from '#components/ui/input.ts';
import { textareaClass } from '#components/ui/textarea.ts';
import { spinner } from '#components/ui/spinner.ts';
import type { submitBugReport } from './form-next-demo-action.server.ts';

export interface BugReportState {
  fieldErrors?: Partial<Record<'title' | 'description', string>>;
  values?: Partial<Record<'title' | 'description', string>>;
}

// One template renders the first paint and the 422 re-render: the page binds
// the action and passes its actionData in as `state` after a failed submission.
export default function BugReportForm(state: BugReportState = {}, action?: typeof submitBugReport) {
  const errors = state.fieldErrors ?? {};
  const values = state.values ?? {};
  return html`
    <form id="bug-report" action=${action} novalidate class="group w-full max-w-md">
      <div data-slot="card" data-size="default" class=${cardClass()}>
        <div data-slot="card-header" class=${cardHeaderClass()}>
          <div data-slot="card-title" class=${cardTitleClass()}>Bug Report</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            Help us improve by reporting bugs you encounter.
          </div>
        </div>
        <div data-slot="card-content" class=${cardContentClass()}>
          <div data-slot="field-group" class=${fieldGroupClass()}>
            <div data-slot="field" data-orientation="vertical" data-invalid=${errors.title ? 'true' : nothing} class=${fieldClass()}>
              <label data-slot="field-label" for="bug-report-title" class=${fieldLabelClass()}>Bug Title</label>
              <input
                data-slot="input"
                id="bug-report-title"
                name="title"
                value=${values.title ?? ''}
                placeholder="Login button not working on mobile"
                autocomplete="off"
                aria-invalid=${errors.title ? 'true' : nothing}
                aria-describedby=${errors.title ? 'bug-report-title-error' : nothing}
                class=${cn(inputClass(), 'group-aria-busy:opacity-50')}
              >
              ${errors.title ? html`
                <div role="alert" data-slot="field-error" id="bug-report-title-error" class=${fieldErrorClass()}>${errors.title}</div>
              ` : ''}
            </div>
            <div data-slot="field" data-orientation="vertical" data-invalid=${errors.description ? 'true' : nothing} class=${fieldClass()}>
              <label data-slot="field-label" for="bug-report-description" class=${fieldLabelClass()}>Description</label>
              <textarea
                data-slot="textarea"
                id="bug-report-description"
                name="description"
                rows="6"
                placeholder="I'm having an issue with the login button on mobile."
                aria-invalid=${errors.description ? 'true' : nothing}
                aria-describedby=${errors.description ? 'bug-report-description-desc bug-report-description-error' : 'bug-report-description-desc'}
                class=${cn(textareaClass(), 'min-h-24 resize-none group-aria-busy:opacity-50')}
              >${values.description ?? ''}</textarea>
              <p data-slot="field-description" id="bug-report-description-desc" class=${fieldDescriptionClass()}>
                Include steps to reproduce, expected behavior, and what actually happened.
              </p>
              ${errors.description ? html`
                <div role="alert" data-slot="field-error" id="bug-report-description-error" class=${fieldErrorClass()}>${errors.description}</div>
              ` : ''}
            </div>
          </div>
        </div>
        <div data-slot="card-footer" class=${cardFooterClass()}>
          <button type="submit" data-slot="button" data-variant="default" data-size="default" class=${cn(buttonClass(), 'group-aria-busy:pointer-events-none group-aria-busy:opacity-50')}>
            ${spinner({ decorative: true, class: 'hidden group-aria-busy:inline-block' })}
            Submit
          </button>
        </div>
      </div>
    </form>
  `;
}
```

**Note:** The examples on this page intentionally set `novalidate` on the form, to show how validation and form errors work in a server action. The demo is live: submit it with short values to see the errors, with or without JavaScript.

## Approach

This form leverages WebJs's built-in form handling. We'll build our form with the Field helpers, which give you **complete flexibility over the markup and styling**.

- A native `<form>` bound to a server action with `action=${submitBugReport}`, which submits with JavaScript off and through the client router with it on.
- The Field helpers (`fieldClass()`, `fieldLabelClass()`, `fieldErrorClass()`) for building accessible forms.
- `actionData` on the page for the form state and errors.
- The `aria-busy` attribute the router sets on a submitting form for loading states.
- Server-side validation in the action, returning `fieldErrors`.

## Anatomy

Here's a basic example of a form using the Field helpers.

```ts
<form action=${submitBugReport}>
  <div data-slot="field-group" class=${fieldGroupClass()}>
    <div data-slot="field" data-invalid=${errors.title ? 'true' : nothing} class=${fieldClass()}>
      <label data-slot="field-label" for="title" class=${fieldLabelClass()}>Bug Title</label>
      <input
        data-slot="input"
        id="title"
        name="title"
        value=${values.title ?? ''}
        aria-invalid=${errors.title ? 'true' : nothing}
        placeholder="Login button not working on mobile"
        autocomplete="off"
        class=${inputClass()}
      >
      <p data-slot="field-description" class=${fieldDescriptionClass()}>
        Provide a concise title for your bug report.
      </p>
      ${errors.title ? html`<div role="alert" data-slot="field-error" class=${fieldErrorClass()}>${errors.title}</div>` : ''}
    </div>
  </div>
  <button type="submit" data-slot="button" class=${buttonClass()}>Submit</button>
</form>
```

## Usage

### Validate the form data

We'll start with the rules the form data has to meet. Write the checks in the action, as below, or call the schema library of your choice there. Whatever you use, turn its result into a `fieldErrors` object keyed by field name.

### Define the form state type

Next, the shape the action returns and the page reads. An action returns the `ActionResult` envelope, and on a failure the page receives it as `actionData`.

```ts title="app/bugs/new/page.ts"
type FormState = {
  fieldErrors?: Record<string, string>;
  values?: Record<string, string>;
};
```

`fieldErrors` is what the action returned. `values` is filled in for you: on a failure it carries every text field that was submitted.

### Create the Server Action

A server action is a function in a `.server.ts` file marked `'use server'`. It runs on the server, and a form bound to it posts its `FormData` to it. We'll use it to validate the form data and decide what the page shows next.

```ts title="modules/bugs/actions/submit-bug-report.server.ts"
'use server';

import type { ActionResult } from '@webjsdev/server';

export async function submitBugReport(formData: FormData): Promise<ActionResult> {
  const title = String(formData.get('title') ?? '').trim();
  const description = String(formData.get('description') ?? '').trim();

  const fieldErrors: Record<string, string> = {};
  if (title.length < 5) fieldErrors.title = 'Bug title must be at least 5 characters.';
  else if (title.length > 32) fieldErrors.title = 'Bug title must be at most 32 characters.';
  if (description.length < 20) fieldErrors.description = 'Description must be at least 20 characters.';
  else if (description.length > 100) fieldErrors.description = 'Description must be at most 100 characters.';

  if (Object.keys(fieldErrors).length) {
    return { success: false, fieldErrors };
  }

  // Do something with the values.
  // Call your database or API here.

  return { success: true };
}
```

**Note:** The action does not return the submitted values. On a failure, the page's `actionData.values` already carries every submitted text field, so the form can refill itself. Return `values` only to normalize or clear a field.

### Build the form

We can now build the form with the Field helpers. The page imports the action and binds it to the form, and reads `actionData` for the errors and the typed values.

```ts title="app/bugs/new/page.ts"
import { html, nothing } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
  cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import {
  fieldGroupClass, fieldClass, fieldLabelClass, fieldDescriptionClass, fieldErrorClass,
} from '#components/ui/field.ts';
import { inputClass } from '#components/ui/input.ts';
import { textareaClass } from '#components/ui/textarea.ts';
import { spinner } from '#components/ui/spinner.ts';
import { submitBugReport } from '#modules/bugs/actions/submit-bug-report.server.ts';

type FormState = {
  fieldErrors?: Record<string, string>;
  values?: Record<string, string>;
};

export default function NewBugReport({ actionData }: { actionData?: FormState }) {
  const errors = actionData?.fieldErrors ?? {};
  const values = actionData?.values ?? {};
  return html`
    <form action=${submitBugReport} novalidate class="group">
      <div data-slot="card" class=${cn(cardClass(), 'w-full max-w-md')}>
        <div data-slot="card-header" class=${cardHeaderClass()}>
          <div data-slot="card-title" class=${cardTitleClass()}>Bug Report</div>
          <div data-slot="card-description" class=${cardDescriptionClass()}>
            Help us improve by reporting bugs you encounter.
          </div>
        </div>
        <div data-slot="card-content" class=${cardContentClass()}>
          <div data-slot="field-group" class=${fieldGroupClass()}>
            <div data-slot="field" data-invalid=${errors.title ? 'true' : nothing} class=${fieldClass()}>
              <label data-slot="field-label" for="title" class=${fieldLabelClass()}>Bug Title</label>
              <input
                data-slot="input"
                id="title"
                name="title"
                value=${values.title ?? ''}
                placeholder="Login button not working on mobile"
                autocomplete="off"
                aria-invalid=${errors.title ? 'true' : nothing}
                aria-describedby=${errors.title ? 'title-error' : nothing}
                class=${inputClass()}
              >
              ${errors.title ? html`
                <div role="alert" data-slot="field-error" id="title-error" class=${fieldErrorClass()}>${errors.title}</div>
              ` : ''}
            </div>
            <div data-slot="field" data-invalid=${errors.description ? 'true' : nothing} class=${fieldClass()}>
              <label data-slot="field-label" for="description" class=${fieldLabelClass()}>Description</label>
              <textarea
                data-slot="textarea"
                id="description"
                name="description"
                rows="6"
                aria-invalid=${errors.description ? 'true' : nothing}
                aria-describedby=${errors.description ? 'description-desc description-error' : 'description-desc'}
                class=${cn(textareaClass(), 'min-h-24 resize-none')}
              >${values.description ?? ''}</textarea>
              <p data-slot="field-description" id="description-desc" class=${fieldDescriptionClass()}>
                Include steps to reproduce, expected behavior, and what actually happened.
              </p>
              ${errors.description ? html`
                <div role="alert" data-slot="field-error" id="description-error" class=${fieldErrorClass()}>${errors.description}</div>
              ` : ''}
            </div>
          </div>
        </div>
        <div data-slot="card-footer" class=${cardFooterClass()}>
          <button type="submit" data-slot="button" class=${cn(buttonClass(), 'group-aria-busy:pointer-events-none group-aria-busy:opacity-50')}>
            ${spinner({ decorative: true, class: 'hidden group-aria-busy:inline-block' })}
            Submit
          </button>
        </div>
      </div>
    </form>
  `;
}
```

### Done

That's it. You now have a fully accessible form with server-side validation that works with or without JavaScript.

When you submit the form, the browser posts it to the page's own URL, and WebJs runs the bound action on the server.

If the form data is invalid, the action returns the errors, and the page re-renders with them at status `422`. If the form data is valid, the response is a `303` redirect back to the page, or to the `redirect` path the action returns. With JavaScript on, the client router does the same over `fetch` and swaps the result in without a reload.

## Pending States

While a form submits through the client router, the router sets `aria-busy="true"` on the `<form>` and back to `"false"` when the response is applied. Put `group` on the form and style its contents with the `group-aria-busy:` variant to show loading indicators.

```ts
<form action=${submitBugReport} class="group">
  <div data-slot="field" class=${cn(fieldClass(), 'group-aria-busy:opacity-50')}>
    <label data-slot="field-label" for="name" class=${fieldLabelClass()}>Name</label>
    <input data-slot="input" id="name" name="name" class=${inputClass()}>
  </div>
  <button type="submit" data-slot="button" class=${cn(buttonClass(), 'group-aria-busy:pointer-events-none group-aria-busy:opacity-50')}>
    ${spinner({ decorative: true, class: 'hidden group-aria-busy:inline-block' })}
    Submit
  </button>
</form>
```

The router also dispatches `webjs:submit-start` and `webjs:submit-end` events on the form, for a component that needs to react in script. With JavaScript off, the browser's own page load is the pending state.

## Disabled States

### Submit Button

To make the submit button inert while the form is submitting, use the `group-aria-busy:` variant on the button, since the busy state is an attribute on the form.

```ts
<button type="submit" data-slot="button" class=${cn(buttonClass(), 'group-aria-busy:pointer-events-none group-aria-busy:opacity-50')}>
  ${spinner({ decorative: true, class: 'hidden group-aria-busy:inline-block' })}
  Submit
</button>
```

### Field

To apply a disabled state and styling to a field, put `data-disabled="true"` on the field and `disabled` on the control.

```ts
<div data-slot="field" data-disabled="true" class=${fieldClass()}>
  <label data-slot="field-label" for="name" class=${fieldLabelClass()}>Name</label>
  <input data-slot="input" id="name" name="name" disabled class=${inputClass()}>
</div>
```

## Validation

### Server-side Validation

Validate the `FormData` in the action and return the failures as `fieldErrors`.

```ts title="modules/bugs/actions/submit-bug-report.server.ts"
export async function submitBugReport(formData: FormData): Promise<ActionResult> {
  const title = String(formData.get('title') ?? '').trim();

  if (title.length < 5) {
    return { success: false, fieldErrors: { title: 'Bug title must be at least 5 characters.' } };
  }

  return { success: true };
}
```

An action can also declare its validation as a `validate` export beside it. The framework calls it with the submitted `FormData` before the action runs, and a `{ success: false, fieldErrors }` result re-renders the page without running the action. See [Server Actions](https://webjs.dev/docs/server-actions).

### Business Logic Validation

You can add additional custom validation logic in your server action, such as a check against the database.

```ts title="modules/auth/actions/sign-up.server.ts"
export async function signUp(formData: FormData): Promise<ActionResult> {
  const email = String(formData.get('email') ?? '').trim();

  if (!email.includes('@')) {
    return { success: false, fieldErrors: { email: 'Enter a valid email address.' } };
  }

  // Check if email already exists in database.
  const [existing] = await db.select().from(users).where(eq(users.email, email));

  if (existing) {
    return { success: false, fieldErrors: { email: 'This email is already registered.' } };
  }

  return { success: true, redirect: '/welcome' };
}
```

## Displaying Errors

Display errors next to the field with `fieldErrorClass()`. Make sure to add `data-invalid="true"` to the field and `aria-invalid="true"` to the control, and point the control's `aria-describedby` at the error so a screen reader reads it.

```ts
<div data-slot="field" data-invalid=${errors.email ? 'true' : nothing} class=${fieldClass()}>
  <label data-slot="field-label" for="email" class=${fieldLabelClass()}>Email</label>
  <input
    data-slot="input"
    id="email"
    name="email"
    type="email"
    value=${values.email ?? ''}
    aria-invalid=${errors.email ? 'true' : nothing}
    aria-describedby=${errors.email ? 'email-error' : nothing}
    class=${inputClass()}
  >
  ${errors.email ? html`<div role="alert" data-slot="field-error" id="email-error" class=${fieldErrorClass()}>${errors.email}</div>` : ''}
</div>
```

Render the error element only when there is an error, so `aria-describedby` never points at an id that is not on the page.

## Resetting the Form

A successful submission redirects, so the page renders fresh and the form is empty. A failed one re-renders the same page, so what was typed is kept.

### Reset on Success

To reset the form on success, return `{ success: true }`. The response is a `303` redirect, and the page it lands on has no `actionData`, so every field renders empty. Return a `redirect` path to land somewhere else.

```ts title="modules/bugs/actions/submit-bug-report.server.ts"
export async function submitBugReport(formData: FormData): Promise<ActionResult> {
  // Validation.
  if (Object.keys(fieldErrors).length) {
    return { success: false, fieldErrors };
  }

  // Business logic.
  await callYourDatabaseOrAPI(formData);

  // A success redirects, so the form renders empty.
  return { success: true };
}
```

### Preserve on Validation Errors

On a failure, the page receives every submitted text field in `actionData.values`. Render each control's value from it, which is what keeps the input when JavaScript is off.

```ts
<input data-slot="input" id="title" name="title" value=${values.title ?? ''} class=${inputClass()}>
<textarea data-slot="textarea" id="description" name="description" class=${textareaClass()}>${values.description ?? ''}</textarea>
```

With JavaScript on, the client router also puts back what was typed into any control the re-render did not set, so a field you forget to refill is not emptied. Passwords and files are never restored. Opt a form out with `data-preserve-values="false"`. To clear a field after a failure, return a `values` entry for it, which wins over the submitted one.
