rich-domain provides built-in validation support using the Standard Schema specification. This means you can use your favorite validation library - Zod, Valibot, ArkType, or any other Standard Schema-compatible library.
import { z } from "zod";import { Id } from "@woltz/rich-domain";const productSchema = z.object({ id: z.custom<Id>((val) => val instanceof Id), name: z.string().min(1, "Name is required"), price: z.number().positive("Price must be positive"), stock: z.number().int().min(0, "Stock cannot be negative"), status: z.enum(["draft", "published", "archived"]),});type ProductProps = z.infer<typeof productSchema>;
Only applies when throwOnError is false. Controls how updates behave while the entity is invalid:
Value
Update behavior
true (default)
Dirty / form mode — mutations apply even when schema or rules fail; validationErrors is refreshed to match the current state (same idea as invalid data on create).
false
Freeze mode — no property changes while validationErrors already exist; updates that would fail validation are reverted.
// Form: user can edit every field; UI reads validationErrors (default)config: { throwOnError: false }// Strict: entity cannot change until all errors are clearedconfig: { throwOnError: false, persistInvalidMutations: false }
With persistInvalidMutations: true, toJSON(), getChanges(), and repository save() may see invalid props. Check hasValidationErrors before persisting.
The ValidationError class provides rich error information:
try { const product = new Product({ name: "", price: -10, ... });} catch (error) { if (ValidationError.isValidationError(error)) { // Get all error messages error.getMessages(); // ["Name is required", "Price must be positive"] // Get errors for specific field error.getErrorsForPath("price"); // [{ path: ["price"], message: "Price must be positive" }] // Check if specific field has errors error.hasErrorsForPath("name"); // true // Access raw issues error.issues; // [ // { path: ["name"], message: "Name is required" }, // { path: ["price"], message: "Price must be positive" } // ] // Serialize for API response error.toJSON(); // { name: "ValidationError", message: "...", issues: [...] } }}