Tillitsdone
down Scroll to discover

Creating Reusable Validation Schemas with Zod

Learn how to build maintainable and type-safe React applications using Zod for data validation.

Discover best practices for creating reusable validation schemas and integrating with React Hook Form.
thumbnail

Abstract geometric shapes flowing like waves representing data validation with interconnected nodes and flowing lines. Dominated by bright cyan blue and metallic silver colors overhead view with dynamic perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Creating Reusable Validation Schemas with Zod in React Projects

If you’ve ever built a form in React, you know the importance of proper data validation. Enter Zod: a TypeScript-first schema validation library that’s changing the game for React developers. Today, let’s dive into how we can create reusable validation schemas with Zod that’ll make our React projects more maintainable and type-safe.

Flowing abstract patterns representing structured data featuring geometric shapes in bright orange and warm golden tones against a clean background side-angle view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Why Zod?

Think of Zod as your data’s bouncer – it ensures only the right data gets into your application. Unlike traditional validation libraries, Zod brings TypeScript integration that’s so seamless, it feels like it was meant to be there all along.

Building Your First Schema

Let’s start with something we all deal with: user registration forms. Instead of writing validation logic scattered across your components, you can create a single, reusable schema:

import { z } from "zod";
export const userSchema = 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"),
confirmPassword: z.string()
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ["confirmPassword"]
});

Landscape of rolling waves formed by structured grid patterns featuring bright emerald green and metallic gold accents captured from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Making Schemas Reusable

The real power of Zod comes from its composability. You can break down complex schemas into smaller, reusable pieces:

const addressSchema = z.object({
street: z.string(),
city: z.string(),
country: z.string(),
postalCode: z.string()
});
const contactSchema = z.object({
phone: z.string(),
email: z.string().email()
});
const customerSchema = z.object({
name: z.string(),
details: contactSchema,
address: addressSchema
});

Practical Usage in React Forms

Here’s where it all comes together. Using Zod with React Hook Form creates a powerful combination:

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
const UserForm = () => {
const { register, handleSubmit, errors } = useForm({
resolver: zodResolver(userSchema)
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{/* Your form fields here */}
</form>
);
};

Best Practices

  1. Keep your schemas in separate files for better organization
  2. Use meaningful error messages that guide users
  3. Create base schemas that can be extended for specific use cases
  4. Take advantage of Zod’s TypeScript integration for better IDE support

Conclusion

Zod doesn’t just validate data – it helps you build more robust React applications. By creating reusable validation schemas, you’re not just saving time; you’re establishing a consistent way to handle data across your entire project.

Abstract fluid forms representing data flow and validation combining contemporary brown and warm copper tones birds-eye view 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.