Blog>
Snippets

Integrating Zod Schema with TanStack Form

Detail the process of integrating a Zod schema for validation into a TanStack Form hook, to validate form input fields in real-time.
import { z } from 'zod';
const userSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  age: z.number().min(18, 'You must be at least 18 years old'),
});
This piece of code defines a Zod schema for user validation. It ensures that the 'name' field is a non-empty string and that the 'age' field is a number not less than 18.
import { useForm } from '@tanstack/react-form';
import { zodValidator } from '@tanstack/zod-form-adapter';
This code imports the necessary hooks from TanStack React Form and the Zod validator adapter.
const form = useForm({
  defaultValues: { name: '', age: 0 },
  validate: zodValidator(userSchema)
});
Here, we initialize the form using TanStack's useForm hook. We specify default values for our form fields and integrate our Zod validation schema using the zodValidator function.
const { Form } = form;
return (
  <Form>
    <div>
      <label htmlFor='name'>Name</label>
      <input id='name' {...form.fields.name.getInputProps()} />
    </div>
    <div>
      <label htmlFor='age'>Age</label>
      <input type='number' id='age' {...form.fields.age.getInputProps()} />
    </div>
    <button type='submit'>Submit</button>
  </Form>
);
Finally, we render the form. We use the Form component and getInputProps methods provided by TanStack's useForm hook to automatically manage form elements like inputs, including attaching necessary props for validation.