New to Claude Skills? Learn how to install them →

prowler-cloud on GitHub

Zod 4 Schema Validator

Free

Efficiently validate and parse data with Zod v4 schemas.

Get this skill

Free · Opens the source repo

What Zod 4 Schema Validator does

Zod 4 Schema Validator provides a robust set of tools for validating and parsing data structures using Zod v4 schemas. This skill is particularly useful for developers working with forms, request payloads, and data adapters, allowing them to ensure that incoming data adheres to specified formats and constraints. The skill simplifies the transition from Zod v3 to v4 by offering migration patterns and examples, making it easier for developers to adapt their existing schemas to the latest version.

With Zod 4, users can create complex validation schemas that include primitive types, object schemas, arrays, and unions. The skill supports advanced features such as transformations, refinements, and error handling, enabling developers to define precise validation rules and custom error messages. For instance, it allows for the creation of schemas that enforce minimum and maximum values, mandatory fields, and specific formats like email and UUID.

This skill is ideal for frontend and backend developers who need to implement data validation in their applications. It integrates seamlessly with libraries like React Hook Form, allowing for smooth form validation and error handling in user interfaces. By leveraging Zod 4, developers can enhance the reliability of their applications and improve user experience by providing clear feedback on input errors.

Overall, Zod 4 Schema Validator is a valuable tool for anyone looking to implement effective data validation strategies in their projects, ensuring that data integrity is maintained throughout the application lifecycle.

When to use it

Use this skill when creating or updating Zod v4 schemas for various data validation tasks, including forms and API request payloads.

When not to use it

This skill may not be suitable for projects that do not use Zod for schema validation or for those requiring validation libraries other than Zod.

What you can build with it

Form Validation in React

Utilize Zod 4 to define schemas for form inputs, ensuring user data meets specified criteria before submission.

API Request Validation

Implement Zod 4 schemas to validate incoming request payloads in your backend services, enhancing data integrity.

Data Migration from Zod 3

Use the provided migration patterns to update your existing Zod 3 schemas to the new syntax and features of Zod 4.

How to install Zod 4 Schema Validator

View source

1. Install with the skills CLI

npx skills add prowler-cloud/prowler/zod-4 --agent claude-code

2. Or install it manually

Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.

Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs

Inside SKILL.md

Written by prowler-cloud

Breaking Changes from Zod 3

// ❌ Zod 3 (OLD)
z.string().email()
z.string().uuid()
z.string().url()
z.string().nonempty()
z.object({ name: z.string() }).required_error("Required")

// ✅ Zod 4 (NEW)
z.email()
z.uuid()
z.url()
z.string().min(1)
z.object({ name: z.string() }, { error: "Required" })

Basic Schemas

import { z } from "zod";

// Primitives
const stringSchema = z.string();
const numberSchema = z.number();
const booleanSchema = z.boolean();
const dateSchema = z.date();

// Top-level validators (Zod 4)
const emailSchema = z.email();
const uuidSchema = z.uuid();
const urlSchema = z.url();

// With constraints
const nameSchema = z.string().min(1).max(100);
const ageSchema = z.number().int().positive().max(150);
const priceSchema = z.number().min(0).multipleOf(0.01);

Object Schemas

const userSchema = z.object({
  id: z.uuid(),
  email: z.email({ error: "Invalid email address" }),
  name: z.string().min(1, { error: "Name is required" }),
  age: z.number().int().positive().optional(),
  role: z.enum(["admin", "user", "guest"]),
  metadata: z.record(z.string(), z.unknown()).optional(),
});

type User = z.infer<typeof userSchema>;

// Parsing
const user = userSchema.parse(data);  // Throws on error
const result = userSchema.safeParse(data);  // Returns { success, data/error }

if (result.success) {
  console.log(result.data);
} else {
  console.log(result.error.issues);
}

Arrays and Records

// Arrays
const tagsSchema = z.array(z.string()).min(1).max(10);
const numbersSchema = z.array(z.number()).nonempty();

// Records (objects with dynamic keys)
const scoresSchema = z.record(z.string(), z.number());
// { [key: string]: number }

// Tuples
const coordinatesSchema = z.tuple([z.number(), z.number()]);
// [number, number]

Unions and Discriminated Unions

// Simple union
const stringOrNumber = z.union([z.string(), z.number()]);

// Discriminated union (more efficient)
const resultSchema = z.discriminatedUnion("status", [
  z.object({ status: z.literal("success"), data: z.unknown() }),
  z.object({ status: z.literal("error"), error: z.string() }),
]);

Transformations

// Transform during parsing
const lowercaseEmail = z.email().transform(email => email.toLowerCase());

// Coercion (convert types)
const numberFromString = z.coerce.number();  // "42" → 42
const dateFromString = z.coerce.date();      // "2024-01-01" → Date

// Preprocessing
const trimmedString = z.preprocess(
  val => typeof val === "string" ? val.trim() : val,
  z.string()
);

Refinements

const passwordSchema = z.string()
  .min(8)
  .refine(val => /[A-Z]/.test(val), {
    message: "Must contain uppercase letter",
  })
  .refine(val => /[0-9]/.test(val), {
    message: "Must contain number",
  });

// With superRefine for multiple errors
const formSchema = z.object({
  password: z.string(),
  confirmPassword: z.string(),
}).superRefine((data, ctx) => {
  if (data.password !== data.confirmPassword) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Passwords don't match",
      path: ["confirmPassword"],
    });
  }
});

Optional and Nullable

// Optional (T | undefined)
z.string().optional()

// Nullable (T | null)
z.string().nullable()

// Both (T | null | undefined)
z.string().nullish()

// Default values
z.string().default("unknown")
z.number().default(() => Math.random())

Error Handling

// Zod 4: Use 'error' param instead of 'message'
const schema = z.object({
  name: z.string({ error: "Name must be a string" }),
  email: z.email({ error: "Invalid email format" }),
  age: z.number().min(18, { error: "Must be 18 or older" }),
});

// Custom error map
const customSchema = z.string({
  error: (issue) => {
    if (issue.code === "too_small") {
      return "String is too short";
    }
    return "Invalid string";
  },
});

React Hook Form Integration

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

const schema = z.object({
  email: z.email(),
  password: z.string().min(8),
});

type FormData = z.infer<typeof schema>;

function Form() {
  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("email")} />
      {errors.email && <span>{errors.email.message}</span>}
    </form>
  );
}

Frequently asked questions about Zod 4 Schema Validator

Similar skills