Skip to content

Forms and validation

Kiln's forms work without JavaScript. A form posts to a page's action, the server reads the body, validates it, and either saves it or returns errors. This guide covers reading request bodies, describing the expected fields with v, and reporting errors back to the form.

Reading a body

readBody(request) reads a JSON or form body into a plain object:

ts
import { readBody } from "@kiln-js/server";

const body = await readBody(request);
// { title: "Hello", published: "on" }

Rules:

  • A body with content-type: application/json must be a JSON object. Anything else gives {}.
  • A body with multipart/form-data or application/x-www-form-urlencoded is read as form fields. Only text fields are kept. File uploads are dropped, so handle files yourself with request.formData().
  • Any other content type gives {}.

Describing the fields

v builds field descriptions. A schema is an object of fields:

ts
import { v } from "@kiln-js/core";

export const PostForm = {
  title: v.string().min(3).max(120),
  email: v.string().email(),
  age: v.number().int().min(13).optional(),
  published: v.boolean(),
  status: v.enum(["draft", "live"] as const),
};

Field types:

  • v.string(): trims the value. Use .min, .max, .email(), or .matches(regex).
  • v.number(): converts numeric strings. Use .min, .max, or .int().
  • v.boolean(): true for on, true, or 1. A missing checkbox is false, so an unchecked box is never an error.
  • v.enum([...]): the value must be one of the listed strings.

Every field can be marked .optional(). A missing or empty optional field is undefined in the result. A missing required field fails with This field is required.

Checks run in order, and the first failure is the message for that field. Each check can take a custom message:

ts
v.string().min(3, "Titles need at least three characters.")

Validating

validate(schema, input) runs each field and returns a result. parseForm reads the body and runs validate in one call:

ts
import { parseForm } from "@kiln-js/server";
import { PostForm } from "./schema";

export async function action({ request }: { request: Request }) {
  const result = await parseForm(request, PostForm);

  if (!result.ok) {
    return Response.json({ errors: result.errors, values: result.values }, { status: 422 });
  }

  await createPost(result.data);
  return redirect("/posts");
}

The result is one of two shapes:

  • { ok: true, data }: every field passed. data has the typed values.
  • { ok: false, errors, values }: errors maps each failing field to its message. values is the raw input, for redisplaying the form.

Showing errors in a page

A form can read errors from a query string or from the data the page loads. A simple pattern uses a loader that reads the errors from the request, and a page that shows them:

tsx
export function loader({ request }: { request: Request }) {
  const url = new URL(request.url);
  return { error: url.searchParams.get("error") };
}

export default function Contact({ data }: { data: { error: string | null } }) {
  return (
    <form method="post">
      {data.error && <p role="alert">{data.error}</p>}
      <input name="email" />
      <button>Send</button>
    </form>
  );
}

If the action redirects back to the same page with ?error=…, the message appears after a failed submission.

Using the schema in the browser

@kiln-js/core has no browser-only code, so you can import a schema in a client component and call validate before submitting. Use the same schema on the server, so the rules are written once. Always validate again on the server. Browser validation is a convenience, not a security check.

Forms and CSRF

A form that posts to a page with CSRF protection turned on must include the token. See Security.

Example

tsx
// app/pages/contact.tsx
import { parseForm, csrfToken, CsrfField } from "@kiln-js/server";
import { v } from "@kiln-js/core";

const ContactForm = {
  name: v.string().min(2),
  email: v.string().email(),
  message: v.string().min(10).max(2000),
};

export function loader({ request }: { request: Request }) {
  return { csrf: csrfToken(request) };
}

export async function action({ request }: { request: Request }) {
  const result = await parseForm(request, ContactForm);
  if (!result.ok) {
    const first = Object.values(result.errors)[0] ?? "Check the form.";
    return redirect(`/contact?error=${encodeURIComponent(String(first))}`);
  }
  await sendMessage(result.data);
  return redirect("/contact?sent=1");
}

export default function Contact({ data }: { data: { csrf: string } }) {
  return (
    <form method="post">
      <CsrfField token={data.csrf} />
      <input name="name" />
      <input name="email" type="email" />
      <textarea name="message" />
      <button>Send</button>
    </form>
  );
}

In a real file, import redirect from @kiln-js/core next to v. The example leaves that import out to keep the focus on the form.