# Validating with a schema

> Validate and type a form with Zod or any other Standard Schema, no plugin needed.

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

Any [Standard Schema](https://standardschema.dev) validates a form: Zod,
Valibot, ArkType and the rest. Core reads it through the standard interface,
so no plugin is needed. Try `admin` as the username.

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

// Still no plugins. Any Standard Schema validates.
const forms = createForms();

const SignUp = z.object({
  username: z.string().min(3, "Use at least 3 characters."),
  email: z.email("Enter a valid email."),
});

const signUp = forms.define({
  schema: SignUp,
  // Without a schema plugin, give every starting value.
  defaultValues: { username: "", email: "" },
  // Runs alongside the schema.
  validate: {
    fields: {
      username: (name) => (name === "admin" ? { message: "That name is reserved." } : undefined),
    },
  },
  onSubmit: (value) => `Signed up ${value.username}.`,
});

export default function SignUpForm() {
  const form = useForm(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="email">{(field) => <TextInput field={field} label="Email" type="email" />}</form.Field>
          <button type="submit">Sign up</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>
  );
}
```

## A schema for the form

`schema` validates the whole value and gives the form its type. Without a
plugin for the schema's library, `defaultValues` is required and complete:

```ts
import { z } from "zod";

const SignUp = z.object({
  username: z.string().min(3, "Use at least 3 characters."),
  email: z.email("Enter a valid email."),
});

const signUp = forms.define({
  schema: SignUp,
  defaultValues: { username: "", email: "" },
  onSubmit: (value) => `Signed up ${value.username}.`,
});
```

`onSubmit` runs only when the schema passes, and gets the schema's output, so a
transform or a coercion in the schema reaches it. `ctx.input` holds the value
before the schema ran.

## A schema for one field

A schema whose input fits the field's type can stand in for a validator
function, in `validate.fields` or in a `validate` prop:

```ts
const signUp = forms.define({
  defaultValues: { username: "", email: "" },
  validate: { fields: { email: z.email("Enter a valid email.") } },
});
```

The form's type still comes from `defaultValues`.

## A schema and validators

A definition can have a schema and validators at once, and both run. Use the
schema for the shape and validators for what it can't say well, or for checks
that need a request:

```ts
const signUp = forms.define({
  schema: SignUp,
  defaultValues: { username: "", email: "" },
  validate: {
    fields: {
      username: (name) => (name === "admin" ? { message: "That name is reserved." } : undefined),
    },
  },
});
```

The schema's errors come first in `field.errors`, then the form validator's,
then the field validators'.

## Starting values from the schema

Writing `defaultValues` that match the schema is repetitive for a large form.
The [schema plugins](https://forms.lunarhue.dev/react/plugins/schemas.md) work them out from the schema, so
`defaultValues` becomes optional.
