Skip to content
typebox-standard-schema

TanStack Form

TanStack Form takes any Standard Schema as a form validator, so a schema built with this package's Type validates the form without an adapter. Issues are routed to fields by their path.

bun

bun add @tanstack/react-form typebox-standard-schema

A complete form

import { useForm } from '@tanstack/react-form'
import { Type } from 'typebox-standard-schema'

const User = Type.Object({
  id: Type.Readonly(Type.Integer()),
  email: Type.String({ format: 'email' }),
  password: Type.Writeonly(Type.String({ minLength: 8 })),
})

const CreateUser = Type.Write(User) // { email, password }

export function SignupForm() {
  const form = useForm({
    defaultValues: { email: '', password: '' },
    validators: { onChange: CreateUser },
    onSubmit: ({ value }) => api.createUser(value),
  })

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault()
        void form.handleSubmit()
      }}
    >
      <form.Field name="email">
        {field => (
          <label>
            Email
            <input value={field.state.value} onChange={event => field.handleChange(event.target.value)} />
            {field.state.meta.errors.map(error => <p key={error?.message}>{error?.message}</p>)}
          </label>
        )}
      </form.Field>
      <form.Field name="password">
        {field => (
          <input type="password" value={field.state.value} onChange={event => field.handleChange(event.target.value)} />
        )}
      </form.Field>
      <button type="submit">Sign up</button>
    </form>
  )
}

api stands for your client. The field names are type-checked against the schema: <form.Field name="id"> is a compile error, because id is read-only and not part of Type.Write(User).

Validate again on the server

TanStack Form submits its own form state rather than the validated output, so a stray field in that state reaches onSubmit. That's fine for the browser, but the server must not trust it: validate the request there with the same schema, through your framework's integration or parse, and the projection strips anything the client may not set.