Implementing Zod Validation with useForm
Showcase how to integrate Zod for defining and applying validation schemas within TanStack Form to ensure type-safe input validation for a registration form.
import { z } from 'zod';
import { zodValidator } from '@tanstack/zod-form-adapter';
import { useForm } from '@tanstack/react-form';
Import necessary modules from Zod for schema creation, the zodValidator from TanStack's Zod form adapter for integration, and useForm from TanStack Form for form creation.
const registrationSchema = z.object({
firstName: z.string().min(1, 'First Name is required'),
lastName: z.string().min(1, 'Last Name is required'),
email: z.string().email('Invalid email address')
});
Define a validation schema using Zod for user registration, ensuring that the first name, last name, and email adhere to specified rules.
function RegistrationForm() {
const form = useForm({
defaultValues: {
firstName: '',
lastName: '',
email: ''
},
validatorAdapter: zodValidator(registrationSchema),
onSubmit: async ({ values }) => {
console.log(values);
}
});
return (
// Form fields and submit button here
);
}
Create the RegistrationForm component. Instantiate the form using useForm, passing in default values for the form fields and specifying the Zod schema through the validatorAdapter. Define an async onSubmit function to handle form submission.