# Validation

> Check fields with your own functions, and choose when errors show.

Source: https://forms.lunarhue.dev/solid/basics/validation

Every form can validate, with no plugin installed. Submit the demo empty, then
type two passwords that differ.

```tsx title="sign-up.tsx"
import { createForm, createForms, inputProps } from "@lunarhue/forms-solid";
import { For, Show } from "solid-js";
import { TextInput } from "./TextInput";

const forms = createForms();

const signUp = forms.define({
  defaultValues: { username: "", password: "", confirm: "", terms: false },
  validate: {
    // One function per field. Return an error, or undefined when it passes.
    fields: {
      username: (name) => (name.length < 3 ? { message: "Use at least 3 characters." } : undefined),
      password: (password) => (password.length < 8 ? { message: "Use at least 8 characters." } : undefined),
    },
    // Sees the whole value, so it can compare two fields.
    form: (value) =>
      value.confirm === value.password ? undefined : { fields: { confirm: { message: "The passwords don't match." } } },
  },
  onSubmit: (value) => `Signed up ${value.username}.`,
});

export default function SignUpForm() {
  const form = createForm(signUp, { id: "sign-up" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.Field name="username">{(field) => <TextInput field={field} label="Username" />}</form.Field>
          <form.Field name="password">
            {(field) => <TextInput field={field} label="Password" type="password" />}
          </form.Field>
          <form.Field name="confirm">
            {(field) => <TextInput field={field} label="Repeat the password" type="password" />}
          </form.Field>
          {/* A validator from the component, added while it is mounted. */}
          <form.Field name="terms" validate={(accepted) => (accepted ? undefined : { message: "Accept the terms." })}>
            {(field) => (
              <div>
                <label>
                  <input {...inputProps(field, { kind: "checkbox" })} />I accept the terms
                </label>
                <ul id={field.errorId}>
                  <For each={field.shownErrors}>{(error) => <li>{error.message}</li>}</For>
                </ul>
              </div>
            )}
          </form.Field>
          <button type="submit">Sign up</button>
          <p role="status">
            <Show when={form.state.submission.status === "succeeded" && form.state.submission}>
              {(submission) => submission().result}
            </Show>
          </p>
        </form>
      )}
    </form.Form>
  );
}
```

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

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.
// Read it through `props`: destructuring stops it updating.
export function TextInput(props: TextInputProps) {
  return (
    <div>
      <label for={props.field.id}>{props.label}</label>
      <input {...inputProps(props.field, { type: props.type ?? "text" })} />
      <ul id={props.field.errorId}>
        <For each={props.field.shownErrors}>{(error) => <li>{error.message}</li>}</For>
      </ul>
    </div>
  );
}
```

## Field validators

`validate.fields` is shaped like the value. Give a field a function that
returns an error, or `undefined` when the value passes:

```ts
const signUp = forms.define({
  defaultValues: { username: "", password: "", confirm: "", terms: false },
  validate: {
    fields: {
      username: (name) => (name.length < 3 ? { message: "Use at least 3 characters." } : undefined),
      password: (password) => (password.length < 8 ? { message: "Use at least 8 characters." } : undefined),
    },
  },
});
```

The function gets the field's value, typed. A Standard Schema for that one
field works in place of the function. See
[Validating with a schema](https://forms.lunarhue.dev/solid/basics/schema-validation.md).

## Form validators

`validate.form` gets the whole value, so it can compare fields. It returns
errors keyed by dotted field name, and each one lands on its field:

```ts
validate: {
  form: (value) =>
    value.confirm === value.password
      ? undefined
      : { fields: { confirm: { message: "The passwords don't match." } } },
},
```

`form` in the same object holds errors for the form as a whole. At an array, a
one-element tuple in `validate.fields` applies its entry to every item:
`{ lines: [{ sku: checkSku }] }`.

## Validators from a component

The `validate` prop on `form.Field` adds a validator while the field is
mounted, and removes it and its errors on unmount:

```tsx
<form.Field name="terms" validate={(accepted) => (accepted ? undefined : { message: "Accept the terms." })}>
  {(field) => <input {...inputProps(field, { kind: "checkbox" })} />}
</form.Field>
```

Inside a component, `createValidator(handle, validator)` does the same, for
the life of the current owner. To make it conditional, create it under
`<Show>`:

```ts
createValidator(form.root.at("terms"), mustAccept);
```

A field that isn't rendered isn't checked by its component validators, so a
submit can pass without them. Rules that must always hold belong in the
definition. `handle.registerValidator(validator)` adds one from anywhere and
returns the function that removes it.

## When validators run

A validator first runs on the field's first blur. After that it runs on every
input. To change the first run, set `validate` on `createForms` to `"input"`,
`"blur"` or `"submit"` for every form, `validate.on` in a definition for one
form, or `on` on one validator:

```ts
username: { validate: checkName, on: "input" },
```

A submit runs every validator and stops if any field has an error.
`field.validate()` runs one field's validators now and resolves true when it
is valid. `form.store.validate()` runs them all.

## Showing errors

`field.errors` has every error on the field. `field.shownErrors` has the ones
the user should see now, and `aria-invalid` follows it. Render
`shownErrors`.

The `show` setting decides. Set it on `createForms` for every form or on
`define` for one:

| `show` | Errors show |
| --- | --- |
| `"touched-or-submitted"` | after the field is blurred or the form submitted (the default) |
| `"touched"` | after the field is blurred |
| `"submitted"` | after the first submit |
| `"always"` | at once |

A function works too. It gets `touched`, `edited`, `dirty` and `submitCount`
and returns true to show.

## Errors you set

`field.invalid` is true when the field has any error, including ones you set
with `setErrors`, such as a server's answer. Those sit in `field.userErrors`
too. They don't block a submit, since the form's `valid` counts validation
errors only, and the next edit clears them. [Submit](https://forms.lunarhue.dev/solid/basics/submit.md) shows how to
put server errors on fields.

`errors` lists validation errors in a fixed order: the schema's, then the form
validator's, then field validators' in the order they were added. To tell them
apart, pass a handle to `errorsByKind`. It returns `{ schema, form, field }`
and leaves out what `setErrors` set. It reads once, so call it again when the
field's `errors` change:

```ts
import { errorsByKind } from "@lunarhue/forms-solid";

const { schema, form, field } = errorsByKind(store.root.at("email"));
```
