Skip to Content

TanStack Form

Use a generated schema as a form validator in TanStack Form.

TanStack Form accepts a Standard Schema as a validator. Valibot and Zod both implement it, so a generated schema of either library fits.

The repository has a complete form in examples/react-forms/src/forms/TanStackForm.tsx.

Validator

import { useForm } from "@tanstack/react-form";
import { create } from "@bufbuild/protobuf";
import { CreateUserRequestSchema } from "./gen/example/v1/user_pb";
import { CreateUserRequestValidationSchema as schema } from "./gen/example/v1/user_pvschema";

const form = useForm({
  defaultValues,
  validators: { onSubmit: schema },
  onSubmit: async ({ value }) => {
    const result = await schema["~standard"].validate(value);
    if (result.issues === undefined) {
      const request = create(CreateUserRequestSchema, result.value);
    }
  },
});

TanStack Form passes the form values to onSubmit, not the output of the schema. Validate once more to get the output. The output has the default of an unset oneof, and its type is the init shape of the message.

Default values

The type of defaultValues is the input type of the schema. A new form holds values that the schema rejects, such as an unselected enum, so the example casts its initial values.

const defaultValues = {
  name: "",
  role: Role.UNSPECIFIED,
  points: 0n,
  contact: { case: undefined },
  agreed: false,
} as unknown as FormInput;

Fields

A field holds the typed value, and the input is controlled. Convert in the change handler, and keep the previous value when the text is not a number.

<form.Field name="points">
  {(field) => (
    <>
      <input
        inputMode="numeric"
        value={String(field.state.value ?? "")}
        onChange={(event) => {
          if (isIntegerText(event.target.value)) {
            field.handleChange(parseOptionalBigInt(event.target.value) as bigint);
          }
        }}
      />
      <p role="alert">{field.state.meta.errors[0]?.message}</p>
    </>
  )}
</form.Field>

An error is the issue object of the schema library, so read its message.

oneof

Give the case and the value a field each: contact.case and contact.value. To change the case, replace the whole oneof with form.setFieldValue("contact", ...).

Do not edit the value through the parent field contact. The error of contact.value then stays after the user fixes the value, and the form does not submit.

Languages

After a language switch, validate a submitted form again.

useEffect(() => {
  if (form.state.submissionAttempts > 0) {
    void form.validate("submit");
  }
}, [lang, form]);