Schema-based Validation with TanStack Form and Zod
Provide an example of using Zod alongside TanStack Form to implement schema-based validation, highlighting how to define schemas and apply them to form fields for validation.
import { useForm } from '@tanstack/react-form';
import { zodValidator } from '@tanstack/zod-form-adapter';
import { z } from 'zod';
Import statements for using TanStack Form with Zod validation.
const schema = z.object({
firstName: z.string().min(1, 'First name is required'),
lastName: z.string().min(1, 'Last name is required'),
email: z.string().email('Enter a valid email address')
});
Define the schema for the form using Zod. This specifies the fields present in the form and validation rules for each.
const { getFieldProps, handleSubmit } = useForm({
validate: zodValidator(schema)
});
Set up the useForm hook with Zod validation by passing the schema through the zodValidator function.
const submitForm = (values) => {
console.log('Form submitted with values:', values);
};
Define a submit function to handle form submission logic, logging the form values to the console.
return (
<form onSubmit={handleSubmit(submitForm)}>
<input type='text' {...getFieldProps('firstName')} />
<input type='text' {...getFieldProps('lastName')} />
<input type='email' {...getFieldProps('email')} />
<button type='submit'>Submit</button>
</form>
);
Render the form with input fields for first name, last name, and email. Use getFieldProps to automatically bind validation and handle changes.