Validate a form with schema and React Hook Form
Separate input, parsed values and submission
React Hook Form manages registration, errors and submission; Zod describes runtime data rules. A resolver connects them. Native inputs can remain uncontrolled using register, while a controlled widget needs a Controller adapter. A schema may transform input, so use z.input and z.output when the two shapes differ. The following examples use compatible React Hook Form 7, Zod 4 and resolver 5 versions as a proposed lane; review exact peer dependencies and type declarations before running. All submissions are local fixtures.
import React,{useState} from 'react';import {useForm} from 'react-hook-form';import {z} from 'zod';import {zodResolver} from '@hookform/resolvers/zod';const schema=z.object({title:z.string().trim().min(2,'Enter at least two characters')});export default function App(){ const [saved,setSaved]=useState(''); const {register,handleSubmit,formState:{errors}}=useForm<z.input<typeof schema>,unknown,z.output<typeof schema>>({resolver:zodResolver(schema),defaultValues:{title:''}}); return <form noValidate onSubmit={handleSubmit(data=>setSaved(data.title),()=>setSaved(''))}> <label htmlFor="title">Supply request title</label><input id="title" {...register('title')} aria-invalid={!!errors.title} aria-describedby={errors.title?'title-error':undefined}/> {errors.title&&<p id="title-error" role="alert">{errors.title.message}</p>}<button>Save</button><p role="status">{saved?`Saved: ${saved}`:''}</p></form>;}An empty or one-letter title produces an associated error; typing two or more nonblank characters and submitting shows the trimmed title. noValidate lets the schema own the validation message instead of native browser popups. The input/output shapes are both strings here, but the explicit generics remain useful when parsing changes the type. The form does not contact a server.
Adapt a controlled widget without double registration
import React,{useState} from 'react';import {Controller,useForm} from 'react-hook-form';type Values={delivery:'pickup'|'desk'};export default function App(){const [saved,setSaved]=useState('');const {control,handleSubmit}=useForm<Values>({defaultValues:{delivery:'pickup'}}); return <form onSubmit={handleSubmit(data=>setSaved(data.delivery))}><Controller name="delivery" control={control} render={({field})=><label>Delivery <select {...field} onChange={e=>field.onChange(e.currentTarget.value)}><option value="pickup">Pickup</option><option value="desk">Desk</option></select></label>}/><button>Save</button><p role="status">{saved}</p></form>;}Pickup starts selected. Choose Desk and submit to display desk. Controller gives the controlled input its value, change handler, blur handler, name and ref. Do not spread register on this same field. A native select can normally use register directly; this deliberately simple adapter demonstrates how controlled components integrate. For custom widgets translate their value and blur events to the field contract and ensure they support accessible names and focus.
Dynamic rows and asynchronous business errors
import React,{useState} from 'react';import {useForm,useFieldArray} from 'react-hook-form';import {z} from 'zod';import {zodResolver} from '@hookform/resolvers/zod';import {saveFixture} from './model';const schema=z.object({title:z.string().trim().min(2,'Enter a title'),items:z.array(z.object({name:z.string().trim().min(1,'Enter an item')})).min(1).max(5),delivery:z.enum(['pickup','desk'])});type Input=z.input<typeof schema>;type Output=z.output<typeof schema>;const initial:Input={title:'',items:[{name:''}],delivery:'pickup'};export default function App(){const [message,setMessage]=useState(''); const {register,control,handleSubmit,setError,reset,formState:{errors,isSubmitting}}=useForm<Input,unknown,Output>({resolver:zodResolver(schema),defaultValues:initial}); const {fields,append,remove}=useFieldArray({control,name:'items'}); async function submit(data:Output){setMessage('');try{const result=await Promise.resolve(saveFixture(data));if(result.kind==='rejected'){setError('root.server',{type:'server',message:result.message});return;}setMessage(`Saved ${result.count} item(s)`);}catch{setError('root.server',{type:'server',message:'Unable to save'});}} return <form noValidate onSubmit={handleSubmit(submit,()=>setMessage(''))}> <fieldset disabled={isSubmitting}><legend>Supply request</legend> <label htmlFor="request-title">Title</label><input id="request-title" {...register('title')} aria-invalid={!!errors.title} aria-describedby={errors.title?'request-title-error':undefined}/>{errors.title&&<p id="request-title-error" role="alert">{errors.title.message}</p>} {fields.map((field,index)=>{const err=errors.items?.[index]?.name;return <div key={field.id}><label htmlFor={`item-${field.id}`}>Item {index+1}</label><input id={`item-${field.id}`} {...register(`items.${index}.name` as const)} aria-invalid={!!err} aria-describedby={err?`error-${field.id}`:undefined}/>{err&&<p id={`error-${field.id}`} role="alert">{err.message}</p>}<button type="button" disabled={fields.length===1} onClick={()=>remove(index)}>Remove item {index+1}</button></div>;})} <button type="button" disabled={fields.length>=5} onClick={()=>append({name:''})}>Add item</button><label>Delivery <select {...register('delivery')}><option value="pickup">Pickup</option><option value="desk">Desk</option></select></label> <button>Save</button><button type="button" onClick={()=>{reset();setMessage('');}}>Reset</button></fieldset> {errors.root?.server&&<p role="alert">{errors.root.server.message}</p>}<p role="status">{isSubmitting?'Saving':message}</p></form>;}Start with one row; add up to five and remove down to one. Use field.id as the React key, not the array index; the registration path uses the current index. Blank rows are invalid. Enter a valid title and Paper to see Saved 1 item(s). Replace the item with Reserved and submit to see Item unavailable. Reset restores the defaults and clears the success message. The promise resolves immediately, so the pending message may not be visible; use a controlled delayed fixture to test it. The controls bound the row count; the schema also checks it. Client-side checks are not a security boundary. A real server validates the request anew, handles conflicts and returns a safe error mapping. Do not collect sensitive submissions or assume one form library is ideal for every form.
Practice
Add a second item, remove the first, submit invalid and valid values, then simulate Reserved. Verify keyboard submission, associated errors, retained values and reset. In a separate controlled test delay the promise and check disabled controls while pending. Verify focus after adding or removing rows; improve focus management if needed.