Tillitsdone
down Scroll to discover

Integrating Zod for Form Validation in React

Learn how to implement robust form validation in React using Zod.

This guide covers basic setup, advanced validation techniques, and best practices for type-safe form handling.
thumbnail

A serene mountain landscape with morning fog featuring bright emerald peaks against a clear sky shot from aerial perspective natural color palette with emphasis on bright greens and whites high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Integrating Zod for Form Validation in React

As developers, we’ve all been there – wrestling with form validation in React applications. While there are many solutions available, Zod has emerged as a powerful and type-safe validation library that seamlessly integrates with React applications. Let’s dive into how we can leverage Zod to create robust form validation systems.

Understanding Zod’s Basic Concepts

Zod is a TypeScript-first schema validation library that helps ensure your data matches the expected shape and type. It’s particularly powerful when combined with React forms because it provides runtime validation with compile-time type inference.

Abstract geometric shapes floating in space composed of white crystalline structures against a deep red background captured from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Setting Up Your Project

First, let’s install the necessary dependencies:

Terminal window
npm install zod react-hook-form @hookform/resolvers/zod

Creating Your First Validated Form

Let’s create a simple registration form with Zod validation:

import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
// Define your validation schema
const registrationSchema = z.object({
username: z.string()
.min(3, 'Username must be at least 3 characters')
.max(20, 'Username cannot exceed 20 characters'),
email: z.string()
.email('Please enter a valid email'),
password: z.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
.regex(/[0-9]/, 'Password must contain at least one number'),
});
// Infer the TypeScript type from the schema
type RegistrationForm = z.infer<typeof registrationSchema>;
const RegistrationForm = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<RegistrationForm>({
resolver: zodResolver(registrationSchema),
});
const onSubmit = (data: RegistrationForm) => {
console.log(data);
// Handle form submission
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<input {...register('username')} placeholder="Username" />
{errors.username && <span>{errors.username.message}</span>}
</div>
<div>
<input {...register('email')} placeholder="Email" />
{errors.email && <span>{errors.email.message}</span>}
</div>
<div>
<input
type="password"
{...register('password')}
placeholder="Password"
/>
{errors.password && <span>{errors.password.message}</span>}
</div>
<button type="submit">Register</button>
</form>
);
};

Ocean waves crashing against rocky cliffs bright turquoise water contrasting with natural stone textures captured from side view perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Advanced Validation Techniques

Zod really shines when handling complex validation scenarios. Here’s how you can implement more advanced validations:

const advancedSchema = z.object({
password: z.string().min(8),
confirmPassword: z.string()
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"], // path of error
});
const customMessages = z.object({
age: z.number()
.min(18, { message: "You must be at least 18 years old" })
.max(100, { message: "Age cannot exceed 100 years" })
});
const conditionalValidation = z.object({
employmentStatus: z.enum(["employed", "unemployed", "student"]),
companyName: z.string().optional()
}).refine(
(data) => {
if (data.employmentStatus === "employed") {
return !!data.companyName;
}
return true;
},
{
message: "Company name is required when employed",
path: ["companyName"],
}
);

Best Practices and Tips

  1. Reusable Schemas: Create base schemas that can be extended for different forms
  2. Custom Error Messages: Use Zod’s error mapping for consistent error messages
  3. Type Safety: Leverage TypeScript integration for better development experience
  4. Async Validation: Implement custom async validators for API-dependent validation

Performance Considerations

When working with Zod, keep these performance tips in mind:

  • Cache your validation schemas outside components
  • Use error mapping for internationalization
  • Implement debouncing for real-time validation

Conclusion

Zod provides a powerful, type-safe approach to form validation in React applications. By combining it with react-hook-form, we get a robust solution that handles both simple and complex validation scenarios while maintaining excellent developer experience.

Flowing abstract liquid shapes in bright creamy colors against a black background featuring smooth curves and dynamic movement captured from top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.