# Async validation

> Check a field against your server while the user types.

Source: https://forms.lunarhue.dev/react/basics/async-validation

A validator that returns a promise is async. Try `ada` as the username.

```tsx title="username.tsx"
import { createForms, useForm } from "@lunarhue/forms-react";
import { TextInput } from "./TextInput";

const forms = createForms();

// Stands in for a request to your server. "ada" and "grace" are taken.
function isTaken(name: string, signal: AbortSignal) {
  return new Promise<boolean>((resolve, reject) => {
    const timer = setTimeout(() => resolve(["ada", "grace"].includes(name)), 600);
    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(signal.reason);
    });
  });
}

const account = forms.define({
  defaultValues: { username: "" },
  validate: {
    fields: {
      username: {
        // A newer run aborts this one's `signal` and drops its result.
        validate: async (name, { signal }) =>
          (await isTaken(name, signal)) ? { message: "That name is taken." } : undefined,
        // Waits for a pause in typing. Submit skips the wait.
        debounce: 400,
        // Checks while the user types, not only after they leave the field.
        on: "input",
      },
    },
  },
  // Shows the answer while the user is still in the field.
  show: "always",
  onSubmit: (value) => `Claimed ${value.username}.`,
});

export default function UsernameForm() {
  const form = useForm(account, { id: "username" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.Field name="username">
            {(field) => (
              <>
                <TextInput field={field} label="Username" />
                <p role="status">{field.validating ? "Checking..." : null}</p>
              </>
            )}
          </form.Field>
          <button type="submit">Claim</button>
          <form.State select={(state) => state.submission}>
            {(submission) => <p role="status">{submission.status === "succeeded" ? submission.result : null}</p>}
          </form.State>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx title="TextInput.tsx"
import { type FieldApi, inputProps } from "@lunarhue/forms-react";

interface TextInputProps {
  readonly field: FieldApi<string>;
  readonly label: string;
  readonly type?: "text" | "email" | "password";
}

// A plain component that takes the field `form.Field` hands its child.
export function TextInput({ field, label, type = "text" }: TextInputProps) {
  return (
    <div>
      <label htmlFor={field.id}>{label}</label>
      <input {...inputProps(field, { type })} />
      <ul id={field.errorId}>
        {field.shownErrors.map((error) => (
          <li key={error.message}>{error.message}</li>
        ))}
      </ul>
    </div>
  );
}
```

```ts
const account = forms.define({
  defaultValues: { username: "" },
  validate: {
    fields: {
      username: {
        validate: async (name, { signal }) =>
          (await isTaken(name, signal)) ? { message: "That name is taken." } : undefined,
        debounce: 400,
        on: "input",
      },
    },
  },
  show: "always",
});
```

An object with `validate` takes options: `debounce` waits for a pause in
typing, and `on` sets when it first runs. The same object works in a
`validate` prop. Errors show once the field is blurred by default, so
`show: "always"` lets the answer appear while the user is still typing. See
[Showing errors](https://forms.lunarhue.dev/react/basics/validation.md#showing-errors).

## Newer runs win

When the user types again, the older run's `signal` aborts and its result is
dropped, so a slow answer never wins over a newer one. Pass the signal to
`fetch`. It also aborts when the field is reset or the validator is removed.

## While it runs

`field.validating` is true while a validator on the field runs, and the form
state's `validating` while any does. Show it next to the input:

```tsx
<form.Field name="username">
  {(field) => (
    <>
      <input {...inputProps(field)} />
      {field.validating ? <p role="status">Checking...</p> : null}
    </>
  )}
</form.Field>
```

## On submit

A submit skips the debounce. It waits for a check that is still running and
goes on only if it passed. A check whose result is still current doesn't run
again. Set `recheckOnSubmit: true` on the validator to run it on every submit
anyway, as for a check that can go stale.
