Tillitsdone
down Scroll to discover

Custom Form Validation With Astro.js & Zod

Learn how to implement a robust form validation system in Astro.js using Zod.

Create type-safe, reliable forms with clear error handling and smooth user experience.
thumbnail

Abstract flowing shapes representing form validation with smooth gradients transitioning from soft creamy whites to gentle yellow tones featuring geometric patterns that suggest data verification and security captured from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Have you ever found yourself wrestling with form validation in your Astro.js projects? Today, we’re diving into creating a robust, type-safe form validation system using the powerful combination of Astro.js and Zod. This approach will not only make your forms more reliable but also provide an excellent developer experience.

Why Zod?

Before we dive in, let’s talk about why Zod is becoming the go-to choice for form validation. Zod brings TypeScript-first schema validation that’s both powerful and intuitive. It’s like having a strict but fair validator that ensures your data is exactly what you expect it to be.

Minimalist geometric patterns flowing like a cascade of data featuring clean lines and shapes in emerald green and white shown from a 45-degree angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Setting Up Our Validation System

Let’s build a practical example that you can adapt for your own projects. We’ll create a contact form that validates user input server-side using Zod schemas. Here’s what we’re going to cover:

  1. Schema Definition
  2. Form Handler Setup
  3. Error Handling
  4. User Feedback

First, let’s define our schema:

import { z } from "zod";
const contactFormSchema = z.object({
name: z.string()
.min(2, "Name must be at least 2 characters")
.max(50, "Name must be less than 50 characters"),
email: z.string()
.email("Please enter a valid email address"),
message: z.string()
.min(10, "Message must be at least 10 characters")
.max(500, "Message must be less than 500 characters"),
});

Implementing the Form Handler

Now that we have our schema set up, let’s create a form handler that processes and validates our data:

export const handleFormSubmission = async (formData: FormData) => {
const rawData = {
name: formData.get("name"),
email: formData.get("email"),
message: formData.get("message"),
};
const result = contactFormSchema.safeParse(rawData);
if (!result.success) {
return {
success: false,
errors: result.error.flatten(),
};
}
// Process validated data here
return {
success: true,
data: result.data,
};
};

Flowing data stream visualization represented by elegant curved lines and dots in bright yellow and white tones captured from a side perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Best Practices and Tips

  1. Always validate both client and server-side
  2. Provide clear, user-friendly error messages
  3. Use TypeScript inference to your advantage
  4. Consider breaking down complex forms into smaller, manageable schemas

Remember, good validation isn’t just about preventing bad data – it’s about creating a smooth, intuitive user experience while maintaining data integrity.

Wrapping Up

By combining Astro.js with Zod, we’ve created a validation system that’s both powerful and developer-friendly. This approach gives us type safety, runtime validation, and a great developer experience all in one package.

Abstract architectural forms suggesting structure and organization with clean lines and shapes in light grey and white tones photographed from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/code-outline.svg AstroJs Blogs
Astro is an all-in-one web framework. It includes everything you need to create a website, built-in.
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.