Use Cases

设计and Implementing Form Validation:Claude Code 实战指南

了解designing and implementing form validation:Claude Code 实战. 包含实用技巧和代码示例。

Let Claude Code Handle Your Form Validation Design

Form validation is an unglamorous but critical feature. Missing input patterns and inconsistent error messages are common issues, and manual implementation is time-consuming. With Claude Code, you can generate everything consistently — from Zod schema definitions to UI components.

Generating Zod Schemas

Let’s create a validation schema for a user registration form.

> Create a Zod validation schema for a signup form.
> Include name, email, password, confirm password, age, and terms agreement.
> Use English error messages.
import { z } from "zod";

export const registerSchema = z
  .object({
    name: z
      .string()
      .min(1, "Please enter your name")
      .max(50, "Name must be 50 characters or less"),
    email: z
      .string()
      .min(1, "Please enter your email address")
      .email("Please enter a valid email address"),
    password: z
      .string()
      .min(8, "Password must be at least 8 characters")
      .regex(/[A-Z]/, "Must contain at least one uppercase letter")
      .regex(/[a-z]/, "Must contain at least one lowercase letter")
      .regex(/[0-9]/, "Must contain at least one number"),
    confirmPassword: z.string().min(1, "Please confirm your password"),
    age: z
      .number({ invalid_type_error: "Age must be a number" })
      .min(13, "You must be at least 13 years old")
      .max(120, "Please enter a valid age"),
    agreement: z.literal(true, {
      errorMap: () => ({ message: "You must agree to the terms of service" }),
    }),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"],
  });

export type RegisterFormData = z.infer<typeof registerSchema>;

Integration with React Hook Form

You can generate a component that combines the schema with React Hook Form in one go.

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { registerSchema, type RegisterFormData } from "./schema";

export function RegisterForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema),
  });

  const onSubmit = async (data: RegisterFormData) => {
    const res = await fetch("/api/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    if (!res.ok) throw new Error("Registration failed");
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div>
        <label htmlFor="name">Name</label>
        <input id="name" {...register("name")} />
        {errors.name && (
          <p className="text-red-500 text-sm">{errors.name.message}</p>
        )}
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input id="email" type="email" {...register("email")} />
        {errors.email && (
          <p className="text-red-500 text-sm">{errors.email.message}</p>
        )}
      </div>

      <div>
        <label htmlFor="password">Password</label>
        <input id="password" type="password" {...register("password")} />
        {errors.password && (
          <p className="text-red-500 text-sm">{errors.password.message}</p>
        )}
      </div>

      <div>
        <label htmlFor="confirmPassword">Confirm Password</label>
        <input
          id="confirmPassword"
          type="password"
          {...register("confirmPassword")}
        />
        {errors.confirmPassword && (
          <p className="text-red-500 text-sm">
            {errors.confirmPassword.message}
          </p>
        )}
      </div>

      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? "Submitting..." : "Register"}
      </button>
    </form>
  );
}

Unified Server-Side Validation

Using the same Zod schema on the server side unifies your validation logic.

import { registerSchema } from "./schema";

// Usage in Express/Next.js API route
export async function POST(request: Request) {
  const body = await request.json();
  const result = registerSchema.safeParse(body);

  if (!result.success) {
    return Response.json(
      { errors: result.error.flatten().fieldErrors },
      { status: 400 }
    );
  }

  // Validation passed - save to DB
  const user = await createUser(result.data);
  return Response.json({ user }, { status: 201 });
}

Adding Validation Rules with Claude Code

Adding validation to existing forms is also easy. After setup following the Claude Code Getting Started Guide, simply ask:

> Add a zip code field to src/components/ProfileForm.tsx.
> Accept the format 12345 or 12345-6789.
> Also add real-time auto-formatting.

Claude Code understands the entire form structure and adds the new field consistently with existing validation rules. For refactoring patterns, see Refactoring Automation.

总结

With Claude Code, you can achieve a consistent design in a short time — from Zod schema definitions to React Hook Form integration and server-side validation. Adding or changing validation rules is done automatically while maintaining consistency with existing code.

For official documentation, see Claude Code.

#Claude Code #validation #forms #Zod #React