Generate Zod Validation Schema and Error Messages using Claude AI
Learn how to leverage AI prompting techniques to efficiently generate type-safe validation schemas with Zod, complete with customized error messages that improve user experience.
Introduction
In modern web development, data validation is a critical yet often tedious task. Zod has emerged as a powerful TypeScript-first schema validation library, but writing comprehensive validation schemas and meaningful error messages can be time-consuming. This article explores how AI tools can streamline this process, helping developers generate robust validation code with custom error messages that enhance user experience.
Example: User Registration Form Validation
Let's say you're building a user registration form that needs to validate several fields: username, email, password, and phone number. Each field has specific requirements:
- Username: 3-20 characters, alphanumeric with underscores only
- Email: Valid email format
- Password: 8+ characters with at least one uppercase letter, one lowercase letter, one number, and one special character
- Phone: Valid international phone number format
Manually coding all these validations with custom error messages would be time-consuming. Here's how you can leverage AI to generate this code quickly.
Using AI to Generate Zod Validation Code
The Prompting Technique
The key to getting high-quality validation code from AI is to provide a clear, structured prompt. Here's an effective format:
Generate a Zod validation schema for the following fields:
[List your fields with requirements]
For each validation rule, include a custom error message that is:
- User-friendly
- Specific about what went wrong
- Instructive on how to fix it
Please format the response as TypeScript code using Zod.
Example Prompt
Generate a Zod validation schema for a user registration form with the following fields:
1. username: 3-20 characters, alphanumeric with underscores only
2. email: Valid email format
3. password: 8+ characters with at least one uppercase letter, one lowercase letter, one number, and one special character
4. phoneNumber: Valid international phone number format
For each validation rule, include a custom error message that is user-friendly, specific about what went wrong, and instructive on how to fix it.
Please format the response as TypeScript code using Zod.
AI-Generated Response
The AI might generate something like this:
import { z } from "zod";
const userRegistrationSchema = z.object({
username: z
.string({
required_error: "Username is required to create your account",
})
.min(3, {
message: "Username must be at least 3 characters long",
})
.max(20, {
message: "Username cannot exceed 20 characters",
})
.regex(/^[a-zA-Z0-9_]+$/, {
message: "Username can only contain letters, numbers, and underscores",
}),
email: z
.string({
required_error: "Email address is required",
})
.email({
message: "Please enter a valid email address (e.g., name@example.com)",
}),
password: z
.string({
required_error: "Password is required to secure your account",
})
.min(8, {
message: "Password must be at least 8 characters long for security",
})
.regex(/[A-Z]/, {
message: "Password must include at least one uppercase letter (A-Z)",
})
.regex(/[a-z]/, {
message: "Password must include at least one lowercase letter (a-z)",
})
.regex(/[0-9]/, {
message: "Password must include at least one number (0-9)",
})
.regex(/[^a-zA-Z0-9]/, {
message: "Password must include at least one special character (e.g., !@#$%)",
}),
phoneNumber: z
.string({
required_error: "Phone number is required",
})
.regex(/^\+[1-9]\d{1,14}$/, {
message: "Please enter a valid international phone number (e.g., +12025551234)",
}),
});
// Type inference
type UserRegistration = z.infer<typeof userRegistrationSchema>;
export { userRegistrationSchema, type UserRegistration };
Enhancing the Prompt for Better Results
To get even better results, you can enhance your prompt with specific examples and requirements:
Generate a Zod validation schema for a user registration form with the following fields:
1. username: 3-20 characters, alphanumeric with underscores only
Example valid: user_123
Example invalid: user@123
2. email: Valid email format
Example valid: user@example.com
Example invalid: user@example
3. password: 8+ characters with at least one uppercase letter, one lowercase letter, one number, and one special character
Example valid: Password123!
Example invalid: password123
4. phoneNumber: Valid international phone number format
Example valid: +12025551234
Example invalid: 2025551234
For each validation rule, include custom error messages that follow these guidelines:
- Friendly and non-technical language
- Specific about what requirement wasn't met
- Clear instructions on how to fix the issue
- No generic messages like "Invalid input"
Also include:
- Required_error messages for each field
- Type inference
- Export the schema and type
Please format the response as TypeScript code using Zod.
Implementation in a React Form
Once you have your AI-generated schema, you can integrate it with your form library of choice. Here's an example with React Hook Form:
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { userRegistrationSchema, UserRegistration } from "./validation";
function RegistrationForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<UserRegistration>({
resolver: zodResolver(userRegistrationSchema),
});
const onSubmit = (data: UserRegistration) => {
console.log(data);
// Submit to your API
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="username">Username</label>
<input id="username" {...register("username")} />
{errors.username && (
<p className="error">{errors.username.message}</p>
)}
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} />
{errors.email && <p className="error">{errors.email.message}</p>}
</div>
<div>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
{...register("password")}
/>
{errors.password && (
<p className="error">{errors.password.message}</p>
)}
</div>
<div>
<label htmlFor="phoneNumber">Phone Number</label>
<input id="phoneNumber" {...register("phoneNumber")} />
{errors.phoneNumber && (
<p className="error">{errors.phoneNumber.message}</p>
)}
</div>
<button type="submit">Register</button>
</form>
);
}
Advanced Techniques
1. Generating Complex Schemas
For more complex validation needs, you can ask the AI to generate schemas with:
- Conditional validation based on other fields
- Custom validation functions
- Nested object structures
- Array validations with specific item requirements
Example prompt for conditional validation:
Generate a Zod validation schema for a payment form where:
1. paymentMethod: Either "creditCard" or "bankTransfer"
2. If paymentMethod is "creditCard", require:
- cardNumber: 16-digit number
- cvv: 3-4 digit number
- expiryDate: MM/YY format
3. If paymentMethod is "bankTransfer", require:
- accountNumber: 10-12 digit number
- routingNumber: 9-digit number
Include friendly, specific error messages for each validation rule.
2. Refining Error Messages
You can also use AI to specifically enhance your error messages:
I have the following Zod validation schema:
[paste your existing schema]
Please improve the error messages to be more:
- User-friendly and conversational
- Specific about what went wrong
- Helpful in explaining how to fix the issue
- Consistent in tone and style
Benefits of AI-Generated Validation
- Time Savings: Generate complex validation logic in seconds rather than writing it manually
- Consistency: Maintain a consistent approach to validation across your application
- Improved UX: Create more user-friendly error messages that help users correct their input
- Type Safety: Leverage Zod's TypeScript integration for end-to-end type safety
- Maintainability: Generate well-structured, readable code that's easier to maintain
Conclusion
Using AI to generate Zod validation schemas and error messages can significantly streamline your development process. By crafting effective prompts and implementing the generated code, you can create robust, user-friendly forms with minimal effort.
Next time you need to implement form validation in your application, consider leveraging AI to generate your Zod schemas and custom error messages. The time saved and the improvement in user experience make this approach well worth exploring.