Standard Schema Validation

Katal v3 features a Universal Validation Engine with first-class native support for the Standard Schema Specification. You can validate incoming requests using Zod, Valibot, ArkType, or Katal's zero-dependency built-in validator without any adapter libraries or performance penalties.


1. Quick Start with Zod

import { Application, Controller } from "katal";
import type { RequestContext } from "katal";
import { z } from "zod";

const app = new Application({ port: 3000 });

// 1. Define Standard Schema
const registerSchema = z.object({
    email: z.string().email(),
    password: z.string().min(8),
    age: z.number().int().min(18).optional(),
});

type RegisterInput = z.infer<typeof registerSchema>;

// 2. Define Action Controller with Static Schema
class RegisterController extends Controller {
    static schema = {
        body: registerSchema,
    };

    async handle(ctx: RequestContext) {
        // Access validated, type-safe data via ctx.valid()
        const body = ctx.valid<RegisterInput>("body");
        return this.created({ email: body.email });
    }
}

// 3. Register route
app.getRouter().post("/api/register", RegisterController);

2. Multi-Target Validation (body, query, params, headers)

Katal validates all request inputs in a single pre-controller pass. You can validate body, query, params, and headers simultaneously:

import { z } from "zod";

const paramsSchema = z.object({
    orgId: z.string().uuid("Invalid organization UUID"),
});

const querySchema = z.object({
    page: z.coerce.number().int().positive().default(1),
    limit: z.coerce.number().int().max(100).default(20),
    search: z.string().optional(),
});

const headersSchema = z.object({
    "x-tenant-id": z.string().min(1),
});

class ListOrgUsersController extends Controller {
    static schema = {
        params: paramsSchema,
        query: querySchema,
        headers: headersSchema,
    };

    async handle(ctx: RequestContext) {
        // Retrieve strongly-typed validated inputs
        const { orgId } = ctx.valid<z.infer<typeof paramsSchema>>("params");
        const { page, limit, search } = ctx.valid<z.infer<typeof querySchema>>("query");
        const tenantId = ctx.valid<z.infer<typeof headersSchema>>("headers")["x-tenant-id"];

        return this.success({ orgId, page, limit, search, tenantId });
    }
}

3. Alternative Standard Schemas (Valibot & ArkType)

Because Katal v3 implements the StandardSchemaV1 interface (~standard property), switching validation libraries requires zero configuration or glue code:

Valibot Example

import * as v from "valibot";

const userSchema = v.object({
    username: v.pipe(v.string(), v.minLength(3)),
    email: v.pipe(v.string(), v.email()),
});

class CreateUserController extends Controller {
    static schema = { body: userSchema };

    async handle(ctx: RequestContext) {
        const body = ctx.valid<v.InferOutput<typeof userSchema>>("body");
        return this.success(body);
    }
}

4. Built-in Zero-Dependency Validator

If you prefer pure zero external runtime dependencies, use Katal's built-in schema validator:

import { Controller, type ValidationSchema } from "katal";

const orderSchema: ValidationSchema = {
    customerEmail: {
        type: "email",
        required: true,
    },
    itemsCount: {
        type: "number",
        required: true,
        min: 1,
        max: 50,
    },
    paymentMethod: {
        type: "enum",
        required: true,
        enum: ["card", "paypal", "apple_pay"],
    },
    shippingAddress: {
        type: "object",
        required: true,
        schema: {
            street: { type: "string", required: true, minLength: 5 },
            zipCode: { type: "string", required: true, pattern: /^\d{5}$/ },
        },
    },
};

class CreateOrderController extends Controller {
    static schema = {
        body: orderSchema,
    };

    async handle(ctx: RequestContext) {
        return this.success(ctx.body);
    }
}

Supported Built-in Rules:

Rule Type Description
type 'string' \| 'number' \| 'boolean' \| 'email' \| 'url' \| 'array' \| 'object' \| 'enum' Expected primitive or format type.
required boolean Rejects undefined or null values.
min / max number Minimum / maximum numerical magnitude.
minLength / maxLength number Minimum / maximum character length (or array length).
pattern RegExp Regular expression pattern match.
enum string[] \| number[] Array of permitted enum literal values.
schema ValidationSchema Recursive schema for nested objects or array items.
custom (val: unknown) => boolean \| string Custom synchronous validation predicate.

5. RFC 7807 / 9457 Problem Details on Validation Failure

When validation fails on any target, Katal immediately aborts request execution and outputs a standardized HTTP 422 Unprocessable Entity Problem Details payload:

{
  "type": "about:blank",
  "title": "Validation Failed",
  "status": 422,
  "detail": "The given data was invalid.",
  "errors": {
    "customerEmail": [
      "customerEmail must be a valid email address"
    ],
    "shippingAddress.zipCode": [
      "shippingAddress.zipCode must match pattern /^\\d{5}$/"
    ]
  }
}

Key features of Katal validation errors: - Exact Nested Object Paths: Deeply nested errors (e.g. shippingAddress.zipCode or items[0].sku) report full path notation. - Comprehensive Error Map: All validation failures across all targets (body, query, params) are aggregated into a single response, saving round-trips for frontend clients.


6. Route-Level Schema Overrides

You can also pass validation schemas directly in route registration options, which take priority over controller static schemas:

app.getRouter().post("/api/checkout", CheckoutController, {
    validation: {
        body: customCheckoutSchema,
    },
});

See Also