Skip to content
typebox-standard-schema

React Hook Form

React Hook Form validates with any Standard Schema through standardSchemaResolver from @hookform/resolvers. A schema built with this package's Type goes straight in, and your submit handler receives the validated output: coerced, defaulted and stripped by the projection.

bun

bun add react-hook-form @hookform/resolvers typebox-standard-schema

A complete form

import type { StandardSchemaV1 } from '@standard-schema/spec'
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema'
import { useForm } from 'react-hook-form'
import { Type } from 'typebox-standard-schema'

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

const CreateUser = Type.Write(User)
type Input = StandardSchemaV1.InferInput<typeof CreateUser>
type Output = StandardSchemaV1.InferOutput<typeof CreateUser>

export function SignupForm() {
  const { register, handleSubmit, formState: { errors } } = useForm<Input, unknown, Output>({
    resolver: standardSchemaResolver(CreateUser),
  })

  return (
    <form onSubmit={handleSubmit(user => api.createUser(user))}>
      <input {...register('email')} />
      {errors.email && <p>{errors.email.message}</p>}

      <input type="number" {...register('age')} />
      {errors.age && <p>{errors.age.message}</p>}

      <input type="password" {...register('password')} />
      {errors.password && <p>{errors.password.message}</p>}

      <button type="submit">Sign up</button>
    </form>
  )
}

api stands for your client. At runtime the inputs hold strings, and coercion turns the age into a number, so the submit handler gets { email: string, age: number, password: string }. The static Input says age: number all the same: this package gives input and output one type, so a defaultValues entry for age is a number too. An empty number input sends '', which is not a number, so a required integer reports it as missing a value of the right type; make the field Type.Optional if it may stay empty. register('id') is a compile error: id is read-only and not part of Type.Write(User).

A missing field gets its own error under its name, so every message lands next to its input.

@standard-schema/spec is only needed for the two type helpers; install it as a dev dependency.