Skip to main content

validate

@rotorsoft/act-root


@rotorsoft/act-root / act/src / validate

Function: validate()

validate<S>(target, payload, schema?): Readonly<S>

Defined in: libs/act/src/utils.ts:252

Validates a payload against a Zod schema.

This is the primary validation function used throughout the Act framework. It parses the payload using the provided Zod schema and throws a ValidationError with detailed error information if validation fails.

When no schema is provided, the payload is returned as-is without validation. This allows for optional validation in the framework.

The framework automatically calls this function when:

  • Actions are invoked via app.do()
  • Events are emitted from action handlers
  • States are initialized

Type Parameters

S

S

Parameters

target

string

Name of the target being validated (used in error messages)

payload

Readonly<S>

The data to validate

schema?

ZodType<S, unknown, $ZodTypeInternals<S, unknown>>

Optional Zod schema to validate against

Returns

Readonly<S>

The validated and type-safe payload

Throws

ValidationError if validation fails with detailed error info

Examples

import { validate } from "@rotorsoft/act";
import { z } from "zod";

const UserSchema = z.object({
email: z.string().email(),
age: z.number().min(0)
});

const user = validate("User", { email: "alice@example.com", age: 30 }, UserSchema);
// Returns: { email: "alice@example.com", age: 30 }
import { validate, ValidationError } from "@rotorsoft/act";
import { z } from "zod";

const schema = z.object({
email: z.string().email(),
age: z.number().min(18)
});

try {
validate("User", { email: "invalid", age: 15 }, schema);
} catch (error) {
if (error instanceof ValidationError) {
console.error("Target:", error.target); // "User"
console.error("Payload:", error.payload); // { email: "invalid", age: 15 }
console.error("Details:", error.details); // Prettified Zod errors
// Details shows: email must be valid, age must be >= 18
}
}
// When schema is undefined, payload is returned as-is
const data = validate("Data", { any: "value" });
// Returns: { any: "value" } without validation
import { state } from "@rotorsoft/act";
import { z } from "zod";

const Counter = state({ Counter: z.object({ count: z.number() }) })
.init(() => ({ count: 0 }))
.emits({ Incremented: z.object({ by: z.number().positive() }) })
.on({ increment: z.object({ by: z.number() }) })
.emit((action) => {
// validate() is called automatically before this runs
// action.by is guaranteed to be a number
return ["Incremented", { by: action.by }];
})
.build();
import { validate } from "@rotorsoft/act";
import { z } from "zod";

const ConfigSchema = z.object({
apiKey: z.string().min(32),
timeout: z.number().positive(),
retries: z.number().int().min(0).max(10)
});

function loadConfig(raw: unknown) {
return validate("AppConfig", raw, ConfigSchema);
}

See