# validonce: full documentation > Every page of the current docs (https://validonce.metatoy.com/docs/next) as plain Markdown, in reading order. Generated from the repository's docs/ folder at build time. --- Source: https://github.com/metatoy/validonce/blob/main/docs/README.md # validonce docs The project overview, install and quick starts are in the [repository README](../README.md). ## Server - [Getting started: ASP.NET Core](getting-started-aspnet.md): a `ValidonceValidator` - [Getting started: FastAPI](getting-started-fastapi.md): a `ValidonceModel` - [Getting started: Fastify](getting-started-fastify.md): `defineRules` and a TypeBox schema - [Getting started: NestJS](getting-started-nestjs.md): `@ValidonceRules` on a DTO - [Getting started: Go](getting-started-go.md): `validonce.MustBuild` with Huma or go-playground/validator - [Getting started: Spring Boot](getting-started-spring.md): a `RuleDefinition` for Java and Kotlin - [Kubernetes custom resources](kubernetes.md): translate CEL `x-kubernetes-validations` to rules ## Client - [React](client-react.md): react-hook-form and Zod - [Angular](client-angular.md): Signal Forms and Reactive Forms - [Vue](client-vue.md): VeeValidate and Zod - [Plain HTML and web components](client-dom.md): `validonce/dom` - [Generated clients](client-codegen.md): the kubb, Hey API and orval plugins - [Loading rules at runtime](live-rules.md): fetch rules when the page loads instead of at build time ## AI tooling - [Migrating an existing project with an agent](agentic-migration.md): the MCP server and the skill, what the agent does, safety, limits and test results - [MCP server](../mcp/README.md): the tools, the differential check and the read-only promise - [Skill: validonce-migrate](../skills/validonce-migrate/SKILL.md): the steps, with per-library guides in [`references/`](../skills/validonce-migrate/references/) and the old-validator runners in [`scripts/`](../skills/validonce-migrate/scripts/README.md) - [AGENTS.md](../AGENTS.md): guidance for coding agents working with validonce ## Reference - [How it works](how-it-works.md): the flow from server rules to browser feedback - [Rule format v1](rule-format-v1.md): the rule kinds, conditions and exact semantics - [How validonce compares](comparison.md): other approaches - [Regex findings](regex-findings.md): portability of `pattern` rules across regex engines - [Releasing](releasing.md): how a release is prepared and published --- Source: https://github.com/metatoy/validonce/blob/main/docs/how-it-works.md # How it works validonce moves cross-field rules from the server to the browser as data, not as code.

How validonce works. 1, server rules: C# with FluentValidation (RequiredWhen, Compare), Python with Pydantic (__rules__), TypeScript with Fastify or NestJS (validonce/rules), Go with Huma (struct rules), Java or Kotlin with Spring Boot (Bean Validation), and Kubernetes CRDs (x-kubernetes-validations in CEL). 2, the OpenAPI document: the rules travel as data under x-validonce on components.schemas, five rule kinds in one format. 3, the browser: the validonce runtime, withRules for Zod, with React (react-hook-form), Angular (Signal and Reactive Forms), Vue (VeeValidate) and web components (validonce/dom). The server always enforces every request; a broken rule returns 422 with the same issue shape, mapped back onto each field.

The sections below follow the rules from left to right: written on the server, exported as data, read and enforced in the browser, and enforced again on the server. ## 1. Write the rules once In C#, a `ValidonceValidator` (a FluentValidation `AbstractValidator`). In Python, `__rules__` on a `ValidonceModel`. In TypeScript, `defineRules` for Fastify or NestJS; in Go, `validonce.MustBuild`; in Java and Kotlin, a `RuleDefinition` for Spring Boot. A Kubernetes CRD's CEL rules are translated instead of rewritten. Each validates requests with its own library and can export the rules. ## 2. Export as data Each object schema in the OpenAPI document gets an `x-validonce` key: ```json { "version": 1, "rules": [ { "id": "Signup.required_when.company", "kind": "required_when", "field": "company", "when": { "eq": { "field": "plan", "value": "pro" } }, "message": { "key": "rules.company_required" } } ] } ``` There are five rule kinds: `required_when`, `compare`, `at_least_one_of`, `exactly_one_of`, `all_or_none`. Field names are wire names (the names in the JSON body). The full format is in [rule-format-v1.md](rule-format-v1.md). Field-level rules (type, length, enum, `pattern`) are not in `x-validonce`. They already travel as standard JSON Schema keywords. ## 3. Evaluate on the client `withRules(schema, rules)` adds one check to a Zod object schema. It runs the rules and returns one Zod issue per failing rule, on the rule's target field. react-hook-form and Angular Signal Forms read the Zod issues. Angular Reactive Forms use `validonceGroupValidator` instead of Zod. Messages are keys, not text. The server sends `rules.company_required`; the client maps it to text with a catalog, so you can translate it. A key with no entry gets a default per rule kind. ## 4. Same result everywhere C#, Python, TypeScript, Go and Java each have their own evaluator. A shared suite in `conformance/` (131 cases) pins the behavior they must agree on. Some of the rules that make this work: - Rules evaluate the JSON wire form, not language objects. - Blank means missing, `null`, `""` or `[]`. Nothing else. - No type coercion: `"1"` is not `1`, and a boolean is never a number. - `compare` passes when either side is blank or has the wrong type. Requiredness is a separate rule. - Dates are `YYYY-MM-DD` strings. Date-times need an offset and compare at millisecond precision. - Each failing rule gives exactly one issue, in rule order. ## 5. The server is the authority Clients may skip checks or run old rules. The server always evaluates every rule, including those marked `server_only`, and answers 422 with the same issue list: - ASP.NET Core: ProblemDetails with a top-level `validonce` array. - FastAPI: `detail` entries of type `validonce.`, with the issue in `ctx`. `issuesFromResponse` in `validonce/server-errors` reads both and returns the same `Issue[]` the client evaluator produces. ## Migrating an existing project Rules do not have to be written from scratch. `validonce-mcp` (an MCP server) and the `validonce-migrate` skill help a coding agent find existing cross-field checks, write them as these rules, and prove the result with a differential check: the old validator and the validonce evaluator run on the same generated inputs and must accept and reject the same ones. The server's tools read, check, evaluate, generate and compare rules; they never run your code. See [agentic-migration.md](agentic-migration.md). ## Known limits - A rule refers only to fields of its own object. A nested object carries its own rules. - Rule kinds are fixed to the five above. Custom predicates do not export. - Evaluators reject a rule-format version they do not know instead of skipping rules. - A `pattern` can still behave differently per regex engine. Run the [regex linter](regex-findings.md) on your OpenAPI document. Guides: [ASP.NET Core](getting-started-aspnet.md), [FastAPI](getting-started-fastapi.md), [Fastify](getting-started-fastify.md), [NestJS](getting-started-nestjs.md), [Go](getting-started-go.md), [Spring Boot](getting-started-spring.md), [Kubernetes](kubernetes.md), [React](client-react.md), [Angular](client-angular.md), [Vue](client-vue.md), [plain HTML](client-dom.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/getting-started-aspnet.md # Getting started: ASP.NET Core > **Try it first:** [the playground with ASP.NET Core](https://playground.metatoy.com/?backend=aspnet&frontend=react) runs this backend live, with React, Angular, Vue or a plain form. Write cross-field rules once in FluentValidation. The server enforces them and publishes them in OpenAPI. Needs .NET 10. ## 1. Install ```sh dotnet add package Validonce.AspNetCore ``` ## 2. Write the validator Derive from `ValidonceValidator`. Ordinary FluentValidation rules (`RuleFor`) work in the same class. ```csharp using System.Text.Json.Serialization; using FluentValidation; using Validonce; using Validonce.FluentValidation; public sealed record Signup( [property: JsonPropertyName("plan")] string? Plan, [property: JsonPropertyName("company")] string? Company, [property: JsonPropertyName("email")] string? Email, [property: JsonPropertyName("start")] DateOnly? Start, [property: JsonPropertyName("end")] DateOnly? End, [property: JsonPropertyName("quantity")] int? Quantity); public sealed class SignupValidator : ValidonceValidator { public SignupValidator() { RequiredWhen(x => x.Company, If.Eq(x => x.Plan, "pro")).WithMessageKey("rules.company_required"); Compare(x => x.End, CompareOp.Ge, x => x.Start).WithMessageKey("rules.end_after_start"); Compare(x => x.Quantity, CompareOp.Ge, 1) .WithMessageKey("rules.quantity_min", new Dictionary { ["min"] = 1 }); RuleFor(x => x.Email).NotEmpty(); } } ``` Group rules take two or more properties: `AtLeastOneOf`, `ExactlyOneOf`, `AllOrNone`. `.AtPath(...)` reports the error on another property. `.ServerOnly()` makes clients skip a rule. ## 3. Register ```csharp using Validonce.AspNetCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddValidonce(); builder.Services.AddOpenApi(o => o.AddValidonceSchemaTransformer()); var app = builder.Build(); app.MapOpenApi(); app.MapPost("/signups", (Signup s) => Results.Ok(new { ok = true })).WithValidonce(); app.Run(); ``` `AddValidonce()` scans the calling assembly. For controllers, call `AddValidonceMvc()` after `AddControllers()`. ## 4. What you get `GET /openapi/v1.json` has the rules under `components.schemas.Signup["x-validonce"]`. A request that breaks a rule gets status 422 (change it with `AddValidonce(o => o.ValidationStatusCode = 400)`): ```json { "title": "One or more validation errors occurred.", "status": 422, "errors": { "Company": ["rules.company_required"] }, "validonce": [ { "path": ["company"], "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {} } ] } ``` `validonce` is the issue list. In the browser, `issuesFromProblemDetails` or `issuesFromResponse` from `validonce/server-errors` turns it back into issues. ## Gotchas - Field names in the rules are wire names: `[JsonPropertyName]` if present, else the camelCase naming policy. Pass your own `JsonSerializerOptions` to the base constructor if you changed the policy. - `Compare` infers its type from the property: numbers, `string`, `DateOnly`, `DateTimeOffset`. `DateTime` is rejected because it has no offset; use `DateTimeOffset` for an instant or `DateOnly` for a date. Numbers are compared as doubles, so a `decimal` loses precision beyond about 15 digits. - Dates travel as ISO strings (`2026-12-01`). Send the same from the browser. - Validators are singletons. Keep them stateless. - Rule ids default to `TypeName.kind.wireField` and must be unique per validator. Use `.WithRuleId(...)` on a collision. ## Migrate with an agent If your cross-field checks are already in FluentValidation (`When`, `Must`, `GreaterThanOrEqualTo(x => x.Other)`), an agent can move them. The [FluentValidation guide](../skills/validonce-migrate/references/fluentvalidation.md) maps each check to a `ValidonceValidator`, and `generate_code` with target `csharp` writes it. The old validator then runs on generated inputs to prove the two agree. See [Migrating with an agent](agentic-migration.md). `suggest_client_wiring` (needs `validonce-mcp` 0.2.0 or later) returns the matching client set-up. Next: the [React guide](client-react.md) or [Angular guide](client-angular.md). Runnable example: [examples/aspnet-app](../examples/aspnet-app/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/getting-started-fastapi.md # Getting started: FastAPI > **Try it first:** [the playground with FastAPI](https://playground.metatoy.com/?backend=fastapi&frontend=react) runs this backend live, with React, Angular, Vue or a plain form. Write cross-field rules once on a Pydantic model. The server enforces them and FastAPI publishes them in OpenAPI. Needs Python 3.10+ and `pydantic>=2.9`. ## 1. Install ```sh pip install validonce ``` ## 2. Write the model ```python from datetime import date from typing import Literal from fastapi import FastAPI from pydantic import Field from validonce import F, ValidonceModel, when class Signup(ValidonceModel): plan: Literal["free", "pro"] company: str | None = None email: str = Field(min_length=1) start: date end: date | None = None quantity: int __rules__ = [ when(F.plan == "pro").require(F.company, key="rules.company_required"), F.end.ge(F.start, key="rules.end_after_start"), F.quantity.ge(1, key="rules.quantity_min", params={"min": 1}), ] app = FastAPI(separate_input_output_schemas=False) @app.post("/signups") def create_signup(body: Signup) -> dict[str, bool]: return {"ok": True} ``` Other builders: `at_least_one_of`, `exactly_one_of`, `all_or_none`, and the condition helpers `all_of`, `any_of`, `not_`. Every builder takes `key=`, `params=`, `id=`, `server_only=` and `message=`. ## 3. What you get `/openapi.json` has the rules under `components.schemas.Signup["x-validonce"]`. `Signup.export_rules()` returns them as a dict. A request that breaks a rule gets 422: ```json {"detail": [{ "type": "validonce.required_when", "loc": ["body", "company"], "msg": "rules.company_required", "input": null, "ctx": {"ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {}} }]} ``` Rules run after field validation succeeds, so a request with a bad field type gets the normal Pydantic errors only. One `ValidationError` lists every failing rule. In the browser, `issuesFromFastApi` or `issuesFromResponse` from `validonce/server-errors` turns the body back into issues. ## Gotchas - **`Signup-Input` and `Signup-Output`.** If a model is both a request body and a `response_model`, FastAPI splits it into two schemas and only `Signup-Input` has `x-validonce`. `rulesFromOpenApi(doc, "Signup")` finds `Signup-Input` for you. Or set `separate_input_output_schemas=False` to keep one `Signup`. - **Naive `datetime`, `bool` and `Decimal` fields are rejected** by `compare` when the class is defined, because they would not compare the same on the wire. Use `AwareDatetime`, `int`/`float`, or pass `type=` for `str` fields that carry dates. - **Rules see the wire form** (`model_dump(mode="json", by_alias=True)`). Field names in rules are aliases. - Dates are ISO strings on the wire. Send `"2026-12-01"`, not a locale format. - Ids default to `ClassName.kind.field`. Pass `id=` on a collision. - Fewer than two fields, a repeated field or an unknown field in a group rule raises `ValidonceDefinitionError` at class definition, not at request time. ## Migrate with an agent If your cross-field checks are already Pydantic `@model_validator`s, an agent can move them. The [Pydantic guide](../skills/validonce-migrate/references/pydantic.md) maps each check to a `ValidonceModel` rule, and `generate_code` with target `python` writes the model. The old validator then runs on generated inputs to prove the two agree. See [Migrating with an agent](agentic-migration.md). `suggest_client_wiring` (needs `validonce-mcp` 0.2.0 or later) returns the matching client set-up. Next: the [React guide](client-react.md) or [Angular guide](client-angular.md). Runnable example: [examples/fastapi-app](../examples/fastapi-app/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/getting-started-fastify.md # Getting started: Fastify > **Try it first:** [the playground with Fastify](https://playground.metatoy.com/?backend=fastify&frontend=react) runs this backend live, with React, Angular, Vue or a plain form. Write cross-field rules once with the TypeScript builders. Fastify enforces them in a `preHandler` and `@fastify/swagger` publishes them in OpenAPI. Needs Node 20+, `fastify>=5` and `@sinclair/typebox`. ## 1. Install ```sh npm install validonce fastify @fastify/swagger @sinclair/typebox ``` ## 2. Write the rules and the route ```ts import swagger from "@fastify/swagger"; import { Type } from "@sinclair/typebox"; import Fastify from "fastify"; import { defineRules, fieldRefs, when } from "validonce/rules"; import { ajvKeywords, swaggerRefResolver, validonceHook, withRules } from "validonce/fastify"; const fields = ["plan", "company", "email", "start", "end", "quantity"] as const; const F = fieldRefs(...fields); const rules = defineRules( "Signup", [ when(F.plan.eq("pro")).require(F.company, { key: "rules.company_required" }), F.end.ge(F.start, { key: "rules.end_after_start", type: "date" }), F.quantity.ge(1, { key: "rules.quantity_min", params: { min: 1 }, type: "number" }), ], { fields }, ); const Signup = withRules( Type.Object( { plan: Type.Union([Type.Literal("free"), Type.Literal("pro")]), company: Type.Optional(Type.Union([Type.String(), Type.Null()])), email: Type.String({ minLength: 1 }), start: Type.String({ format: "date" }), end: Type.Optional(Type.Union([Type.String({ format: "date" }), Type.Null()])), quantity: Type.Integer(), }, { $id: "Signup" }, ), rules, ); const app = Fastify({ ajv: { customOptions: { keywords: ajvKeywords } } }); await app.register(swagger, { openapi: { openapi: "3.1.0", info: { title: "API", version: "1" } }, refResolver: swaggerRefResolver, }); app.addSchema(Signup); app.post( "/signups", { schema: { body: { $ref: "Signup#" } }, preHandler: validonceHook(Signup) }, async () => ({ ok: true }), ); ``` Other builders: `atLeastOneOf`, `exactlyOneOf`, `allOrNone`, and the condition helpers `allOf`, `anyOf`, `not`. Each takes an options object with `key`, and optionally `params`, `id`, `server_only` and `path`. ## 3. What you get `app.swagger()` has the rules under `components.schemas.Signup["x-validonce"]`. A request that breaks a rule gets 422 problem details with a top-level `validonce` member: ```json { "type": "about:blank", "title": "One or more validation errors occurred.", "status": 422, "validonce": [ { "path": ["company"], "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {} } ] } ``` Rules run in a `preHandler`, after Fastify's own schema validation, so a body with a bad field type gets Fastify's 400 and no rule errors. One response lists every failing rule. In the browser, `issuesFromProblemDetails` or `issuesFromResponse` from `validonce/server-errors` turns the body back into issues. ## Gotchas - **Startup errors.** `defineRules` throws `ValidonceDefinitionError` for an unknown field (when you pass `fields`), a duplicate id, an unsupported compare type, or a group rule with fewer than two fields. Call it at module load so the app fails to start. - **Compare type is explicit** (`type: "date"`, `"number"`, …) unless you pass `fields` as a map from name to type. - **Ajv keyword.** Fastify's Ajv runs in strict mode, so pass `keywords: ajvKeywords` (as above) or schema compilation fails on `x-validonce`. - **Component name.** Without `swaggerRefResolver`, `@fastify/swagger` names the schema `def-0`. The resolver names it after `$id`. - Ids default to `Schema.kind.field`. Pass `id:` on a collision. - Rules see the parsed body, so field names are wire names. ## Migrate with an agent Fastify has no dedicated source guide. If your cross-field checks are in Zod, yup or Joi, use the matching guide in [`skills/validonce-migrate/references/`](../skills/validonce-migrate/references/). `generate_code` with target `typescript-rules` and `framework: "fastify"` writes the `defineRules` call and a TypeBox schema (needs `validonce-mcp` 0.2.0 or later). See [Migrating with an agent](agentic-migration.md). Next: the [React guide](client-react.md) or [Angular guide](client-angular.md). Runnable example: [examples/fastify-app](../examples/fastify-app/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/getting-started-nestjs.md # Getting started: NestJS > **Try it first:** [the playground with NestJS](https://playground.metatoy.com/?backend=nestjs&frontend=react) runs this backend live, with React, Angular, Vue or a plain form. Write cross-field rules once with the TypeScript builders. A class decorator carries them, a pipe enforces them and a post-processor publishes them in the `@nestjs/swagger` document. Needs Node 20+ and `@nestjs/common` and `@nestjs/swagger` 11 or later. ## 1. Install ```sh npm install validonce @nestjs/common @nestjs/core @nestjs/platform-express @nestjs/swagger reflect-metadata rxjs ``` ## 2. Write the rules and the class ```ts import { Body, Controller, Post } from "@nestjs/common"; import { ApiBody, ApiProperty } from "@nestjs/swagger"; import { defineRules, fieldRefs, when } from "validonce/rules"; import { ValidonceRules, ValidonceValidationPipe } from "validonce/nestjs"; const fields = ["plan", "company", "email", "start", "end", "quantity"] as const; const F = fieldRefs(...fields); const rules = defineRules( "Signup", [ when(F.plan.eq("pro")).require(F.company, { key: "rules.company_required" }), F.end.ge(F.start, { key: "rules.end_after_start", type: "date" }), F.quantity.ge(1, { key: "rules.quantity_min", params: { min: 1 }, type: "number" }), ], { fields }, ); @ValidonceRules(rules) export class Signup { @ApiProperty({ enum: ["free", "pro"] }) plan!: "free" | "pro"; @ApiProperty({ nullable: true, required: false }) company?: string | null; @ApiProperty({ minLength: 1 }) email!: string; @ApiProperty({ format: "date" }) start!: string; @ApiProperty({ format: "date", nullable: true, required: false }) end?: string | null; @ApiProperty({ type: Number }) quantity!: number; } @Controller("signups") export class SignupsController { @Post() @ApiBody({ type: Signup }) create(@Body(new ValidonceValidationPipe(Signup)) body: Signup) { return { ok: true }; } } ``` Then in `main.ts`: ```ts import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger"; import { addValidonceToDocument, ValidonceExceptionFilter } from "validonce/nestjs"; app.useGlobalFilters(new ValidonceExceptionFilter()); // optional: application/problem+json const document = addValidonceToDocument( SwaggerModule.createDocument(app, new DocumentBuilder().setTitle("API").build()), [Signup], ); SwaggerModule.setup("docs", app, document); ``` Other builders: `atLeastOneOf`, `exactlyOneOf`, `allOrNone`, and the condition helpers `allOf`, `anyOf`, `not`. Each takes an options object with `key`, and optionally `params`, `id`, `server_only` and `path`. ## 3. What you get The document has the rules under `components.schemas.Signup["x-validonce"]`. A request that breaks a rule gets 422 problem details with a top-level `validonce` member (see [Transport](rule-format-v1.md#transport-server-responses)). One response lists every failing rule. In the browser, `issuesFromProblemDetails` or `issuesFromResponse` from `validonce/server-errors` turns the body back into issues. ## Gotchas - **Two pipes, in this order.** Nest's `ValidationPipe` (class-validator decorators on the class) goes first and answers 400 for a bad field; `ValidonceValidationPipe` goes second and answers 422 for broken rules, which assume well-typed fields. As globals: `app.useGlobalPipes(new ValidationPipe(), new ValidonceValidationPipe())`; per parameter: `@Body(new ValidationPipe(), new ValidonceValidationPipe(Signup))`. See [examples/nestjs-app](../examples/nestjs-app/src/app.ts) for the esbuild variant. - **`new ValidonceValidationPipe(Signup)`** names the class. With `emitDecoratorMetadata` (tsc, SWC) a global `new ValidonceValidationPipe()` finds it from the parameter type; esbuild and Vite emit no metadata, so name it. Likewise those builds need `@ApiProperty({ type: … })` and `@ApiBody({ type })`. - **Startup errors.** `defineRules` throws `ValidonceDefinitionError` for an unknown field (when you pass `fields`), a duplicate id or an unsupported compare type; `addValidonceToDocument` throws when a class has no rules or no schema in the document. - **Schema name** is the class name, so `@ValidonceRules` on `Signup` lands on `components.schemas.Signup`. - Without `ValidonceExceptionFilter` the 422 body is the same but its content type is `application/json`. ## Migrate with an agent If your cross-field checks are class-validator decorators or custom validators on a DTO, an agent can move them. The [class-validator guide](../skills/validonce-migrate/references/class-validator.md) maps each check to `@ValidonceRules` and `ValidonceValidationPipe`, and `generate_code` with target `typescript-rules` and `framework: "nestjs"` writes the DTO and rules. The old DTO runs on generated inputs through the Node runner's `class-validator` kind. These need `validonce-mcp` 0.2.0 or later. See [Migrating with an agent](agentic-migration.md). Next: the [React guide](client-react.md) or [Angular guide](client-angular.md). Runnable example: [examples/nestjs-app](../examples/nestjs-app/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/getting-started-go.md # Getting started: Go > **Try it first:** [the playground with Go](https://playground.metatoy.com/?backend=go&frontend=react) runs this backend live, with React, Angular, Vue or a plain form. Write cross-field rules once next to a Go struct. The server enforces them, Huma publishes them in OpenAPI, and the browser forms read them. Needs Go 1.26 or later. ## 1. Install ```sh go get github.com/metatoy/validonce/go ``` The core package has no dependencies beyond the standard library. `github.com/metatoy/validonce/go/humaonce` adds Huma, `github.com/metatoy/validonce/go/playground` adds go-playground/validator. ## 2. Write the struct and the rules ```go type Signup struct { Plan string `json:"plan" enum:"free,pro"` Company *string `json:"company,omitempty" nullable:"true"` Email string `json:"email" minLength:"1"` Start string `json:"start" format:"date"` End *string `json:"end,omitempty" format:"date" nullable:"true"` Quantity int32 `json:"quantity"` } var signupRules = validonce.MustBuild[Signup]( validonce.When(validonce.Eq("plan", "pro")).Require("company", validonce.Key("rules.company_required")), validonce.Cmp("end").Ge(validonce.Ref("start"), validonce.Key("rules.end_after_start")), validonce.Cmp("quantity").Ge(validonce.Val(1), validonce.Key("rules.quantity_min"), validonce.Params(map[string]any{"min": 1})), ) // Publish the rules as x-validonce on the component schema. func (Signup) TransformSchema(_ huma.Registry, s *huma.Schema) *huma.Schema { return humaonce.Transform(signupRules, s) } ``` Wrap the handler so a broken rule returns 422 before your code runs: ```go huma.Post(api, "/signups", humaonce.Wrap(signupRules, func(ctx context.Context, in *struct{ Body Signup }) (*Out, error) { return &Out{}, nil })) ``` Other builders: `AtLeastOneOf`, `ExactlyOneOf`, `AllOrNone`, and the conditions `Ne`, `In`, `Present`, `Absent`, `AllOf`, `AnyOf`, `Not`. Every builder takes `Key`, `Params`, `ID`, `Path` and `ServerOnly`. ## 3. What you get `/openapi.json` has the rules under `components.schemas.Signup["x-validonce"]`. A request that breaks a rule gets 422 as `application/problem+json`, with the issues in a top-level `validonce` member (see "Transport" in the [rule format](rule-format-v1.md)): ```json {"type": "about:blank", "title": "One or more validation errors occurred.", "status": 422, "validonce": [{"path": ["company"], "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {}}]} ``` Rules run after Huma's own field validation succeeds. One response lists every failing rule. In the browser, `issuesFromProblemDetails` or `issuesFromResponse` from `validonce/server-errors` turns the body back into issues. ## With go-playground/validator If you already call `validate.Struct`, register the rules once and they run with your field tags: ```go v := validator.New() playground.Register(v, signupRules, Signup{}) if err := v.Struct(body); err != nil { return playground.FromError(signupRules, err) // a 422 *validonce.Problem for rule failures } ``` Each failing rule is a field error whose tag is the rule id; `playground.IssuesFromError` gives the issues back. ## Gotchas - **Field names are JSON names.** Builders are keyed by the `json` tag (the wire name) and checked by reflection when `Build` runs: an unknown field, a `compare` on an unsupported Go type (a `bool`, a slice), or a duplicate id is an error at startup, not at request time. - **Compare types come from the Go field.** Numbers compare as `number`, `string` fields as `string`, `time.Time` as `datetime`. Dates are strings with `format:"date"`; a string with `format:"date-time"` is a `datetime`. Pass `validonce.As("date")` when the tag is missing. - **Use pointers for optional fields** (`*string`, `omitempty`), so a missing or `null` value reaches the rules as blank. - Rules see the wire form: the struct is encoded with `encoding/json` and the resulting JSON object is evaluated. - Ids default to `TypeName.kind.field`. Pass `ID(...)` on a collision. - Release tags for this module are `go/vX.Y.Z`. ## Migrate with an agent If your cross-field checks are go-playground/validator tags or `RegisterStructValidation` functions, an agent can move them. The [go-playground guide](../skills/validonce-migrate/references/go-playground.md) maps each check to a `validonce.MustBuild[T]` rule set, and `generate_code` with target `go` writes the struct and rules (notes cover Huma and the go-playground adapter). The Go runner runs the old validator on generated inputs. These need `validonce-mcp` 0.2.0 or later. See [Migrating with an agent](agentic-migration.md). Next: the [React guide](client-react.md) or [Angular guide](client-angular.md). Runnable example: [examples/go-app](../examples/go-app/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/getting-started-spring.md # Getting started: Spring Boot > **Try it first:** [the playground with Spring Boot](https://playground.metatoy.com/?backend=spring&frontend=react) runs this backend live, with React, Angular, Vue or a plain form. Write cross-field rules once, next to your request type. The server enforces them inside the normal `@Valid` flow and springdoc publishes them in OpenAPI. Needs Java 21 and Spring Boot 3.5 (Jackson 2, Hibernate Validator, springdoc 2.8). ## 1. Install ```kotlin dependencies { implementation("com.metatoy:validonce-spring:0.5.0") implementation("org.springframework.boot:spring-boot-starter-validation") implementation("org.springdoc:springdoc-openapi-starter-webmvc-api:2.8.17") } ``` `validonce-spring` brings `validonce-core` (rule model, evaluator, builders) and registers itself through Spring Boot auto-configuration. ## 2. Write the rules Fields are Jackson property names, the names in the JSON body. ```java @ValidonceRules(SignupRules.class) public record Signup( @NotNull Plan plan, String company, @NotNull @Size(min = 1) String email, @NotNull LocalDate start, LocalDate end, @NotNull Integer quantity) {} public final class SignupRules extends RuleDefinition { public SignupRules() { super(Signup.class); } @Override protected void define(RuleSetBuilder r) { r.requiredWhen("company", Condition.eq("plan", "pro")).key("rules.company_required") .compare("end", Op.GE, "start").key("rules.end_after_start") .compareValue("quantity", Op.GE, 1).key("rules.quantity_min").param("min", 1); } } @PostMapping("/signups") Map create(@Valid @RequestBody Signup body) { return Map.of("ok", true); } ``` The same in Kotlin: ```kotlin @ValidonceRules(SignupRules::class) data class Signup(val plan: Plan, val company: String?, val email: String, val start: LocalDate, val end: LocalDate?, val quantity: Int) class SignupRules : RuleDefinition(Signup::class.java) { override fun define(r: RuleSetBuilder) { r.requiredWhen("company", Condition.eq("plan", "pro")).key("rules.company_required") .compare("end", Op.GE, "start").key("rules.end_after_start") .compareValue("quantity", Op.GE, 1).key("rules.quantity_min").param("min", 1) } } ``` Other builders: `atLeastOneOf`, `exactlyOneOf`, `allOrNone`, and the conditions `ne`, `in`, `present`, `absent`, `all`, `any`, `not`. After a rule, `.key()`, `.param()`, `.id()`, `.path()`, `.serverOnly()` and `.type()` set its options. ## 3. What you get `/v3/api-docs` has the rules under `components.schemas.Signup["x-validonce"]` (set `springdoc.api-docs.version=openapi_3_1` for an OpenAPI 3.1 document). A request that breaks a rule gets 422 problem details, with every failing rule in a top-level `validonce` member: ```json { "type": "about:blank", "title": "One or more validation errors occurred.", "status": 422, "validonce": [ { "path": ["company"], "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {} } ] } ``` Other `@Valid` failures (such as `@NotNull`) are listed under `errors`, field to messages, in the same 422. In the browser, `issuesFromProblemDetails` or `issuesFromResponse` from `validonce/server-errors` turns the body back into issues. ## Gotchas - **Wrong rules stop startup.** An unknown field, a field type that `compare` does not support (`boolean`, `LocalDateTime`) or two rules with the same id throws when the application starts, not on the first request. This covers types used as controller parameters or return types. - **Rules see the wire form**: the bean serialized with the application's `ObjectMapper`. A `@JsonProperty` or naming strategy changes the names to use in rules. - **`compare` types** are inferred: numbers, `String`, `LocalDate`, and `OffsetDateTime`/`ZonedDateTime`/`Instant`. Use `.type(CompareType.DATE)` for a `String` field that carries dates. - **Rules run beside field constraints**, not after them, so one 422 can carry both `validonce` and `errors`. - **Hibernate Validator** is required (it is the Spring Boot default); the issues travel as violation payloads. - Ids default to `TypeName.kind.field`. Pass `.id(...)` on a collision. - The `x-validonce` schema is matched by the class's simple name, springdoc's default schema name. ## Migrate with an agent If your cross-field checks are Jakarta Bean Validation constraints (class-level validators, `@AssertTrue` methods), an agent can move them. The [Jakarta guide](../skills/validonce-migrate/references/jakarta.md) maps each check to a `RuleDefinition` with `@ValidonceRules`, and `generate_code` with target `java` writes the record and rules (notes cover Kotlin). The Java runner runs the old validator on generated inputs. These need `validonce-mcp` 0.2.0 or later. See [Migrating with an agent](agentic-migration.md). Next: the [React guide](client-react.md) or [Angular guide](client-angular.md). Runnable example: [examples/spring-app](../examples/spring-app/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/client-react.md # Client: React > **Try it first:** [the playground with React](https://playground.metatoy.com/?backend=aspnet&frontend=react) runs this frontend live against ASP.NET Core, FastAPI, Fastify, NestJS, Go, Spring Boot or a Kubernetes CRD. Use the server's rules in a React form with react-hook-form and Zod 4. The same code works against ASP.NET Core and FastAPI. ```sh pnpm add validonce zod react-hook-form @hookform/resolvers ``` ## 1. Load the rules ```ts import { rulesFromOpenApi } from "validonce/openapi"; const doc: unknown = await (await fetch("http://localhost:5080/openapi/v1.json")).json(); const rules = rulesFromOpenApi(doc, "Signup"); // RuleSet | undefined if (!rules) throw new Error("no x-validonce rules for Signup"); ``` FastAPI serves `/openapi.json`, ASP.NET Core serves `/openapi/v1.json`. For FastAPI, `rulesFromOpenApi` also finds `Signup-Input`. To skip the fetch, run `npx validonce extract openapi.json -o src/rules.gen.ts` at build time. ## 2. Attach them to a Zod schema ```tsx import { zodResolver } from "@hookform/resolvers/zod"; import { useMemo } from "react"; import { useForm } from "react-hook-form"; import { withRules } from "validonce/zod"; import { z } from "zod"; const messages: Record = { "rules.company_required": "Company is required on the Pro plan", "rules.end_after_start": "End date must be on or after the start date", "rules.quantity_min": "Quantity must be at least {min}", }; const baseSchema = z.object({ plan: z.enum(["free", "pro"]), company: z.string().nullable(), email: z.string().min(1, "Email is required").email("Enter a valid email"), start: z.string().min(1, "Start date is required"), end: z.string().nullable(), quantity: z.number("Quantity is required"), }); type FormValues = z.input; const schema = useMemo(() => withRules(baseSchema, rules, { messages }), [rules]); const { register, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(schema), defaultValues: { plan: "free", company: null, email: "", start: "", end: null, quantity: 1 }, }); ``` Show `errors.company?.message` under the company input. `{min}` is filled from the rule's params. A key with no entry in `messages` falls back to a default text for the rule kind. Blank inputs must become `null` for nullable fields, or the Zod type check fails first. The example form does it with `register("company", { setValueAs: (v) => (v === "" ? null : v) })`. ## 3. Show server errors The server can still reject a request the browser accepted. Map its 422 body onto the same fields: ```ts import { fieldErrorsFromIssues, issuesFromResponse } from "validonce/server-errors"; const res = await fetch("http://localhost:5080/signups", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values), }); if (!res.ok) { const body: unknown = await res.json().catch(() => null); const serverErrors = fieldErrorsFromIssues(issuesFromResponse(body), messages); // { company: "..." } } ``` `issuesFromResponse` detects the FastAPI body (`detail`) and the ASP.NET body (`validonce`). Nested paths come out dotted, for example `bookings.1.end`. ### The two 422 shapes ASP.NET Core: ```json { "status": 422, "errors": { "Company": ["rules.company_required"] }, "validonce": [{ "path": ["company"], "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {} }] } ``` FastAPI: ```json { "detail": [{ "type": "validonce.required_when", "loc": ["body", "company"], "msg": "rules.company_required", "ctx": { "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {} } }] } ``` ## 4. Re-check dependent fields react-hook-form validates a field when it changes, so an error on `company` goes stale when only `plan` changes. `registerDeps` lists the fields to re-check: ```tsx import { registerDeps } from "validonce/react-hook-form"; const deps = registerDeps(rules); ` (`YYYY-MM-DD`), not `z.date()`. A `Date` object is not a date to the rules. `isoDate()` matches what the servers accept; `z.iso.date()` also lets year `0000` through. - **Zod 4 skips object refinements when a field fails.** A normal `.refine()` on the object would not run while another field is invalid, so errors would appear one at a time. `withRules` adds an always-run check and evaluates the raw input, so rule errors show together with field errors. - `withRules` throws if a rule names a field the schema does not have. This catches renames early. - Rules marked `server_only` are skipped in the browser. - An empty string counts as blank, like `null`, `[]` and a missing key. ## Migrate with an agent If the form's cross-field checks are Zod `refine` or `superRefine`, or yup `when` and `test`, an agent can replace them with `withRules`. The [Zod guide](../skills/validonce-migrate/references/zod.md) and [yup guide](../skills/validonce-migrate/references/yup.md) map each check, `generate_code` with targets `zod` and `react-hook-form` writes the wiring, and `suggest_client_wiring` with `frontend: "react"` returns copy-ready snippets (needs `validonce-mcp` 0.2.0 or later). See [Migrating with an agent](agentic-migration.md). Full working form: [examples/react-form](../examples/react-form/src/App.tsx). Package reference: [js/README.md](../js/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/client-angular.md # Client: Angular > **Try it first:** [the playground with Angular](https://playground.metatoy.com/?backend=aspnet&frontend=angular) runs this frontend live against ASP.NET Core, FastAPI, Fastify, NestJS, Go, Spring Boot or a Kubernetes CRD. Use the server's rules in an Angular form. Signal Forms need no adapter. Reactive Forms use one group validator. Both read the rules from the OpenAPI document. ```sh pnpm add validonce zod ``` ## Load the rules ```ts import { rulesFromOpenApi } from "validonce/openapi"; const doc: unknown = await (await fetch("http://localhost:5080/openapi/v1.json")).json(); const rules = rulesFromOpenApi(doc, "Signup")!; // or generate them: npx validonce extract openapi.json -o src/rules.gen.ts ``` ## Signal Forms The Zod schema implements Standard Schema, so Angular's `validateStandardSchema` accepts it. Errors recompute when any field changes, so an error on `company` clears when only `plan` changes. No extra wiring. ```ts import { signal } from "@angular/core"; import { form, validateStandardSchema } from "@angular/forms/signals"; import { withRules } from "validonce/zod"; import { z } from "zod"; const Signup = z.object({ plan: z.enum(["free", "pro"]), company: z.string().nullable(), start: z.string(), end: z.string().nullable(), }); const messages = { "rules.company_required": "Company is required on the Pro plan", "rules.end_after_start": "End date must be on or after the start date", }; const model = signal({ plan: "free", company: null, start: "", end: null }); const f = form(model, (path) => validateStandardSchema(path, withRules(Signup, rules, { messages })), ); // f.company().errors() -> [{ kind: "standardSchema", message: "Company is required on the Pro plan", ... }] ``` ## Reactive Forms ```ts import { FormControl, FormGroup } from "@angular/forms"; import { validonceGroupValidator } from "validonce/angular"; const group = new FormGroup( { plan: new FormControl("free"), company: new FormControl(""), start: new FormControl(""), end: new FormControl(""), }, { validators: validonceGroupValidator(rules, { messages }) }, ); // group.controls.company.errors -> { validonce: { ruleId, key, params, message } } // group.errors -> { validonce: Issue[] } ``` - The validator reads `group.getRawValue()` and sets a `validonce` error on the control at each issue's path. Other errors on that control stay. - When an issue no longer applies, only the `validonce` error is removed. - A nested `FormGroup` needs its own validator with that object's rules. - Use one validator instance per group. `server_only` rules are skipped. ## Show server errors ```ts import { fieldErrorsFromIssues, issuesFromResponse } from "validonce/server-errors"; // in the HTTP error handler, with the 422 response body: const errors = fieldErrorsFromIssues(issuesFromResponse(body), messages, rules); // { company: "..." } ``` `issuesFromResponse` accepts the ASP.NET Core body (`validonce` member) and the FastAPI body (`detail` list). Passing `rules` as the third argument gives the same default text as the client check. ## Gotchas - **Dates must be ISO strings** (`YYYY-MM-DD`). `` gives that. An empty input is `""`, which counts as blank. - With Signal Forms and Zod 4, `withRules` is needed instead of `.refine()`: Zod 4 skips object refinements when any field fails, and `withRules` uses an always-run check. - `withRules` throws if a rule names a field the schema lacks. - A path with no control in a Reactive Form is ignored on the controls; the issue still appears in `group.errors`. ## Migrate with an agent If the form's cross-field checks are Angular group validators, an agent can replace them with the rules from the server. The [Angular guide](../skills/validonce-migrate/references/angular.md) maps each check, `generate_code` with target `angular-reactive` writes `validonceGroupValidator`, and `suggest_client_wiring` with `frontend: "angular"` returns copy-ready snippets (needs `validonce-mcp` 0.2.0 or later). See [Migrating with an agent](agentic-migration.md). Package reference: [js/README.md](../js/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/client-vue.md # Client: Vue > **Try it first:** [the playground with Vue](https://playground.metatoy.com/?backend=aspnet&frontend=vue) runs this frontend live against ASP.NET Core, FastAPI, Fastify, NestJS, Go, Spring Boot or a Kubernetes CRD. Use the server's rules in a Vue 3 form with VeeValidate and Zod 4. The same code works against ASP.NET Core and FastAPI. ```sh pnpm add validonce zod vee-validate vue ``` ## What VeeValidate accepts Checked against the published packages (May 2026): | Version | `validationSchema` takes | Zod 4 | |---|---|---| | `vee-validate` 4.15.1 (`latest`) | its own `TypedSchema` (`{ __type: "VVTypedSchema", parse() }`) | `@vee-validate/zod` peers `zod ^3.24`, so it does not take Zod 4 | | `vee-validate` 5.0.0-beta.0 (`beta`) | any Standard Schema, directly (`TypedSchema` is gone) | yes, a Zod 4 schema plugs in | So on VeeValidate 4, `validonce/vue` has `toVeeSchema(schema)`, which wraps a Standard Schema (a `withRules` Zod schema) as a `TypedSchema`. On VeeValidate 5, pass the schema straight to `validationSchema` and skip the adapter. The other helper, `watchDependents`, is the same on both. ## 1. Load the rules ```ts import { rulesFromOpenApi } from "validonce/openapi"; const doc: unknown = await (await fetch("http://localhost:5080/openapi/v1.json")).json(); const rules = rulesFromOpenApi(doc, "Signup"); // RuleSet | undefined if (!rules) throw new Error("no x-validonce rules for Signup"); ``` FastAPI serves `/openapi.json`, ASP.NET Core serves `/openapi/v1.json`. To skip the fetch, run `npx validonce extract openapi.json -o src/rules.gen.ts` at build time. ## 2. Attach them to a Zod schema ```vue ``` Show `errors.company` under the company input. `{min}` is filled from the rule's params. A key with no entry in `messages` falls back to a default text for the rule kind. Blank inputs must become `null` for nullable fields, or the Zod type check fails first: ```vue ``` ## 3. Re-check dependent fields VeeValidate validates a field when it changes, so an error on `company` goes stale when only `plan` changes. `watchDependents(form, rules)` watches each field that other rules read and calls the form's `validateField` for the fields where those rules report. Call it once, in `setup()`, after `useForm`. It returns a function that stops the watchers (they also stop with the component). `dependentFields(rules)` (also exported from `validonce/vue` and `validonce/deps`) returns the whole map, for example `{ plan: ["company"], start: ["end"] }`. Rules marked `server_only` are skipped. ## 4. Show server errors The server can still reject a request the browser accepted. Map its 422 body onto the same fields: ```ts import { fieldErrorsFromIssues, issuesFromResponse } from "validonce/server-errors"; const res = await fetch("http://localhost:5080/signups", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values), }); if (!res.ok) { const body: unknown = await res.json().catch(() => null); serverErrors.value = fieldErrorsFromIssues(issuesFromResponse(body), messages, rules); // { company: "..." } } ``` `issuesFromResponse` detects the FastAPI body (`detail`) and the ASP.NET body (`validonce`). The two shapes are shown in [Client: React](client-react.md#the-two-422-shapes). ## Gotchas - **Dates are ISO strings.** Use `isoDate()` from `validonce/zod` (or `z.string()`) with ``, not `z.date()`. - **Zod 4 skips object refinements when a field fails.** `withRules` adds an always-run check and evaluates the raw input, so rule errors show together with field errors. - `withRules` throws if a rule names a field the schema does not have. - VeeValidate 4 validates the whole schema and reads one field's errors from the result, so `validateField("end")` also runs the other rules. This is cheap for form-sized schemas. - `validonce/vue` imports `vue` (for `watch`); `vue` and `vee-validate` are optional peer dependencies of `validonce`. ## Migrate with an agent If the form's cross-field checks are in VeeValidate (a Zod or yup schema passed to `validationSchema`, or `defineRule`), an agent can replace them with `withRules`. The [VeeValidate guide](../skills/validonce-migrate/references/vee-validate.md) maps each check, `generate_code` with target `vue` writes the composable and a single-file component, and `suggest_client_wiring` with `frontend: "vue"` returns copy-ready snippets. These need `validonce-mcp` 0.2.0 or later. See [Migrating with an agent](agentic-migration.md). Full working form: [examples/vue-form](../examples/vue-form/src/SignupForm.vue). Package reference: [js/README.md](../js/README.md#vee-validate-vue). --- Source: https://github.com/metatoy/validonce/blob/main/docs/client-dom.md # Client: plain HTML and web components > **Try it first:** [the playground with a plain HTML form](https://playground.metatoy.com/?backend=aspnet&frontend=dom) runs this frontend live against ASP.NET Core, FastAPI, Fastify, NestJS, Go, Spring Boot or a Kubernetes CRD. Use the server's rules in a plain HTML form, or in a form made of web components (Lit, Stencil, or your own). `validonce/dom` runs the rules in the browser and reports errors through the platform's own validation API, so `validationMessage`, `:invalid` and `form.reportValidity()` all work. It has no framework dependency. The same code works against ASP.NET Core and FastAPI. ```sh pnpm add validonce ``` ## 1. Load the rules ```ts import { rulesFromOpenApi } from "validonce/openapi"; const doc: unknown = await (await fetch("http://localhost:5080/openapi/v1.json")).json(); const rules = rulesFromOpenApi(doc, "Signup"); // RuleSet | undefined if (!rules) throw new Error("no x-validonce rules for Signup"); ``` ## 2. Attach them to the form ```html
``` ```ts import { attachRules } from "validonce/dom"; const messages = { "rules.company_required": "Company is required on the Pro plan", "rules.end_after_start": "End date must be on or after the start date", "rules.quantity_min": "Quantity must be at least {min}", }; const form = document.querySelector("#signup")!; const { validate, applyServerErrors, detach } = attachRules(form, rules, { messages }); ``` What it does: - **Reads the named controls.** A number input gives a number, or `null` when empty. A date input gives the ISO string. An empty text field gives `null`. A checkbox gives a boolean; a radio group gives the checked value. `readForm(form)` returns the same data. - **Evaluates the client rules** (not `server_only` ones) and sets `setCustomValidity` on the control each error belongs to. Every control's custom message is cleared first, because a stale one would block submit. - **Shows the text in an error element**, sets `aria-invalid="true"` on the control and links the two with `aria-describedby`. The element is a live region (`aria-live="polite"`), because the browser's own bubble is unstyled and read out poorly. The element is, in order: `[data-validonce-error=""]` inside the form; one the control's `aria-describedby` already names; else a `

` created after the control's `

`; } firstUpdated() { this.#attached = attachRules(this.querySelector("form")!, this.rules, { messages }); } disconnectedCallback() { this.#attached?.detach(); super.disconnectedCallback(); } } customElements.define("signup-form", SignupForm); ``` ### Stencil Attach in `componentDidLoad`: ```tsx import { Component, Element, h, Prop } from "@stencil/core"; import { attachRules, type Attached } from "validonce/dom"; @Component({ tag: "signup-form", shadow: false }) export class SignupForm { @Element() host!: HTMLElement; @Prop() rules!: RuleSet; attached?: Attached; componentDidLoad() { this.attached = attachRules(this.host.querySelector("form")!, this.rules, { messages }); } disconnectedCallback() { this.attached?.detach(); } render() { return
{/* fields */}
; } } ``` ### The `` element An optional wrapper does the attaching for a `
` inside it. Rules come from the `rules` property, or from a `rules-url` attribute (a rules document, or an OpenAPI document with `schema="Signup"`): ```ts import { defineValidonceForm } from "validonce/dom-element"; defineValidonceForm(); ``` ```html …
``` Set `messages` on the element as a property. It fires `validonce-ready` once attached and `validonce-error` if the rules fail to load, and has `validate()` and `applyServerErrors(body)` methods. ## Shadow-DOM caveat `attachRules` looks at `form.elements`, so the form and its controls must be in the same tree, and the form must be inside the root you pass it. A form in a shadow root works if you attach from inside that component (as in the Lit and Stencil examples). It does not reach across a shadow boundary: a `
` in the light DOM cannot see inputs inside a child component's shadow root unless that component is form-associated. If you wrap native inputs in your own element without form association, make the wrapper form-associated, or render its input into the light DOM. Error elements follow the same rule: `data-validonce-error` and `aria-describedby` are looked up in the form's own tree, and an `aria-describedby` reference cannot cross a shadow boundary. Put the error element next to the control in the same root. ## Migrate with an agent For a plain HTML or web-component form, `generate_code` with target `dom` writes the `attachRules(form, rules)` call and the matching form markup, and `suggest_client_wiring` with `frontend: "dom"` returns the snippets. Both need `validonce-mcp` 0.2.0 or later. If hand-written checks exist in the form, the skill's guides in [`skills/validonce-migrate/references/`](../skills/validonce-migrate/references/) cover the libraries it supports. See [Migrating with an agent](agentic-migration.md). Full working form, with one form-associated custom element: [examples/dom-form](../examples/dom-form/src/main.ts). Package reference: [js/README.md](../js/README.md). --- Source: https://github.com/metatoy/validonce/blob/main/docs/client-codegen.md # Generated clients: kubb, Hey API, orval > **Try it first:** [the playground](https://playground.metatoy.com) runs every backend and frontend pairing live in the browser. If your frontend generates its API client and Zod schemas from OpenAPI, the generated schemas have the field rules (types, enums, formats, required) but not the cross-field ones: generators ignore `x-validonce`. A validonce plugin fixes that. After each generation run it writes one extra file, `validonce.gen.ts`, next to the generator's output. That file re-exports every schema under the same name, with `withRules` attached wherever the OpenAPI schema has `x-validonce`: ```ts // validonce.gen.ts (generated; do not edit) export * from "./zod.gen"; export const zSignup = _withRules(_gen.zSignup, { version: 1, rules: [ /* from x-validonce */ ] }); ``` Change one import (`./zod.gen` becomes `./validonce.gen`), and the form enforces the server's cross-field rules before submit. The rules are copied at generation time: no runtime fetch, and changes show up in code review. The generator's own files are never modified. The schemas are plain Zod 4, so they work with every validonce frontend: `zodResolver` in React, Angular Signal Forms or `validonce/angular`, `toVeeSchema` in Vue. For plain HTML and web components, pass the rules to `attachRules`. The generators themselves need **Node 22.18 or later** (their own requirement); the plugins run wherever the generator runs. The rest of validonce still supports Node 20. ## kubb ```ts // kubb.config.ts import { pluginZod } from "@kubb/plugin-zod"; import { defineConfig } from "kubb/config"; import { pluginValidonce } from "validonce/kubb"; export default defineConfig({ input: "./openapi.json", output: { path: "./src/gen" }, plugins: [pluginZod(), pluginValidonce()], // after pluginZod }); ``` - Works with plugin-zod's default layout (one file per schema under `zod/`) and with a single file (`pluginZod({ output: { path: "./schemas.ts" } })`). Exports are named `signupSchema`. - Options: `zod` (plugin-zod's file or directory, relative to `output.path`), `output` (default `validonce.gen.ts`), `map` (`{ Signup: "exportName" }` when names don't match). - kubb 5.23 or later; the input must be a local OpenAPI JSON file. ## Hey API (`@hey-api/openapi-ts`) ```ts // openapi-ts.config.ts import { defineConfig } from "@hey-api/openapi-ts"; import { validonce } from "validonce/hey-api"; export default defineConfig({ input: "./openapi.json", output: "src/gen", plugins: ["zod", validonce()], }); ``` - Writes `src/gen/validonce.gen.ts` beside `zod.gen.ts`. Exports are named `zSignup`. - Option: `fileName` (default `validonce.gen.ts`). - Needs Zod 4 output (Hey API's default). It stops with an error on `compatibilityVersion: 3` or `mini`. - `@hey-api/openapi-ts` 0.99.x. Its plugin API is still 0.x, so the supported range is narrow and widens as it is tested. ## orval ```js // orval.config.mjs import { withValidonce } from "validonce/orval"; export default withValidonce({ signup: { input: "./openapi.json", output: { client: "zod", mode: "single", target: "./src/gen/schemas.ts", override: { zod: { generateReusableSchemas: true, version: 4 } }, }, }, }); ``` - `withValidonce` adds an input transformer and an `afterAllFilesWrite` hook to every project. Hooks you already have are kept, and the validonce hook runs last. - If you compose hooks yourself, `createValidonce({ zodFile })` returns the two pieces separately. - Options: `fileName` (default `validonce.gen.ts`), `zodFile` (needed unless `output.mode` is `single`), `map`. - Exports keep orval's names (`Signup`). orval only logs errors thrown in hooks, so the validonce hook also sets a failing exit code; CI notices a broken generation. - orval 8. Zod 3 output and the `mini` variant are rejected. ## Any other generator: `validonce wrap` The plugins call the same code as the CLI. For a generator without a plugin, run it after generation: ```sh npx validonce wrap --openapi openapi.json --zod src/gen/schemas.ts -o src/gen/validonce.gen.ts --style auto ``` `--style` is `auto` (default), `orval` (`Signup`), `kubb` (`signupSchema`) or `hey-api` (`zSignup`); `--map Name=export` names any other export. See [js/README.md](../js/README.md). ## Notes - **Aliases.** Generators also export per-operation aliases of a schema (orval `PostSignupsBody`, kubb `postSignupsBodySchema`). These stay unwrapped, and generation prints a warning. Import the component schema (`Signup`, `signupSchema`, `zSignup`) in forms, or name the alias with `map`. - **Schemas that aren't objects** (`allOf` intersections, unions) can't take `withRules`. They're re-exported unchanged with a warning. - **Kubernetes.** The plugins read `x-validonce` from any OpenAPI document. A CRD translated with `validonce k8s` (see [Kubernetes custom resources](kubernetes.md)) works too. ## Migrate with an agent `suggest_client_wiring` with `frontend`, `generator` (`kubb`, `hey-api` or `orval`) and optionally `schemaName` returns the plugin config, the one import change and the export name the generator will use. `read_openapi_rules` also lists those export names per schema as `generatorNames`. Both need `validonce-mcp` 0.2.0 or later. See [Migrating with an agent](agentic-migration.md). Working setups for each generator are in [`examples/codegen-clients`](../examples/codegen-clients). CI regenerates them, fails if the committed output changes, and tests that the generated schemas enforce the Signup rules. --- Source: https://github.com/metatoy/validonce/blob/main/docs/rule-format-v1.md # validonce rule format, version 1 Status: **stable**. Version 1 has shipped in every validonce release since 0.1.0 (2026-11-22). Changes to this file change the contract every implementation is tested against, so each change also updates `conformance/`. See "Change log" and "Errata" at the end. ## Purpose A server writes its cross-field validation rules once, in its own stack: FluentValidation with ASP.NET Core (C#), Pydantic with FastAPI (Python), Fastify or NestJS (TypeScript), Huma or go-playground/validator (Go), or Bean Validation with Spring Boot (Java, Kotlin). Kubernetes custom resources can supply them too, translated from CEL. validonce exports those rules as data in this format. Every evaluator (C#, TypeScript, Python, Go, Java) reads the same data and must reach the same result for the same input. The shared cases in `conformance/rules/` are the proof. Field-level rules (type, length, enum, `pattern`) are not part of this format. They already travel through standard JSON Schema keywords. ## Conformance language and roles The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as described in RFC 2119 and RFC 8174, when they appear in capitals. | Role | What it is | Its duties | |---|---|---| | **Exporter** | Turns rules written in a server's validation library into `x-validonce` data | MUST write only valid rule sets (see "Invalid rule sets"). MUST derive a unique `id` when the author gives none, and fail on a collision. MUST reject a `compare` whose `type` does not match the JSON Schema type of its fields. MUST use wire names | | **Evaluator** | Parses rule data and runs it against an object | MUST reject an invalid rule set as a whole, and a `version` it does not know. MUST follow "Pinned behavior" exactly. MUST return issues in the shape and order of "Issues". MUST pass every case in `conformance/` | | **Host** | The server or client code around an evaluator (a framework integration, a form library adapter) | A server MUST evaluate every rule, `server_only` ones included. A client MUST skip `server_only` rules. A host MUST prefix issue paths for nested objects. A server SHOULD report issues as described in "Transport" | ## Where the data lives On each object schema in an OpenAPI document (or a plain JSON Schema), under the key `x-validonce`: ```json { "type": "object", "properties": { "plan": { "type": "string" }, "company": { "type": ["string", "null"] } }, "x-validonce": { "version": 1, "rules": [ { "id": "Signup.required_when.company", "kind": "required_when", "field": "company", "when": { "eq": { "field": "plan", "value": "pro" } }, "message": { "key": "rules.company_required" } } ] } } ``` The machine-readable schema for this object is `conformance/schema/rule-format-v1.schema.json`. **Canonical URL:** (the schema's `$id`). Evaluators never fetch it; the URL is a stable name, so offline use is unaffected. ## Common rule fields | Field | Required | Meaning | |---|---|---| | `id` | yes | Letters, digits and `_ . : -` only (`^[A-Za-z0-9_.:-]+$`), unique within the rule set. Exporters derive `Model.kind.path` when the author gives none, and fail on a collision | | `kind` | yes | One of the five kinds below | | `path` | no | The field the error is reported on. Defaults per kind (below) | | `message` | yes | `{ "key": string, "params"?: object }`. Params values are strings, numbers, booleans or null | | `server_only` | no | `true` means clients skip the rule. The server always evaluates it | All field names are **wire names**: the names in the JSON body, after aliases and naming policies are applied. A v1 rule refers only to fields of the object it is attached to. A nested object carries its own rules; its issues are reported with the path prefix of where it sits (`["items", "3", "end"]`). Prefixing is the host's job, not the evaluator's. ## Rule kinds | Kind | Fields | Fails when | Default `path` | |---|---|---|---| | `required_when` | `field`, `when` (condition) | `when` is true and `field` is blank | `field` | | `compare` | `left` (`{ "field" }`), `op`, `right` (`{ "field" }` or `{ "value" }`), `type` | both sides pass the type check and the comparison is false | `left.field` | | `at_least_one_of` | `fields` (2 or more) | every listed field is blank | first of `fields` | | `exactly_one_of` | `fields` (2 or more) | the number of non-blank fields is not exactly one | first of `fields` | | `all_or_none` | `fields` (2 or more) | some, but not all, listed fields are blank | first of `fields` | `op` is one of `lt`, `le`, `gt`, `ge`, `eq`, `ne`. `type` is one of `number`, `string`, `date`, `datetime`. `compare` **passes** when either side is blank, and when either side fails its type check. Requiredness is always a separate rule. A constant (`right.value`) must itself pass the type check of `type`: a number for `number`, a string for `string`, a real calendar date for `date`, a datetime with an offset for `datetime`. Otherwise the rule could never fail, so the rule set is invalid (see "Invalid rule sets"). An exporter rejects a `compare` whose `type` does not match the JSON Schema type of its fields, so a type failure at runtime means the data is wrong, and field-level validation reports it. ## Conditions (used by `required_when`) Each condition is an object with exactly one key. | Condition | Shape | True when | |---|---|---| | `eq` | `{ "eq": { "field", "value" } }` | the field's value strictly equals `value` | | `ne` | `{ "ne": { "field", "value" } }` | `eq` would be false (so a blank field makes `ne` true) | | `in` | `{ "in": { "field", "values": [...] } }` | `eq` is true for at least one of `values` | | `present` | `{ "present": { "field" } }` | the field is not blank | | `absent` | `{ "absent": { "field" } }` | the field is blank | | `all` | `{ "all": [conditions] }` (1 or more) | every condition is true | | `any` | `{ "any": [conditions] }` (1 or more) | at least one condition is true | | `not` | `{ "not": condition }` | the condition is false | `value` and the items of `values` are strings, numbers or booleans. `null` is not allowed; use `absent`. ## Invalid rule sets A parser MUST reject a rule set, as a format error, when any of these hold. It never skips a bad rule and keeps the rest. - **The schema rejects it.** Anything `rules-v1.json` rejects is invalid. That covers a missing or unknown `version`, a missing `rules` array, an unknown `kind`, `op`, `type` or condition, and a missing required field. - **Objects are closed.** The rule set, each rule, `message`, `left`, `right` and every condition body allow only the keys this document lists. An unknown key (including `x-` annotations) is an error, not ignored. Descriptions belong on the schema, not inside a rule. - **Ids.** `id` matches `^[A-Za-z0-9_.:-]+$`, and no two rules in a rule set share an id. Issues carry `ruleId`, so duplicates would make them ambiguous. - **Non-empty names.** `message.key`, `path` and every field name are non-empty strings. `server_only` is a boolean. `message.params` values are strings, numbers, booleans or null. - **Groups.** `fields` lists 2 or more distinct names. - **Conditions.** `right` and each condition have exactly one key. `in` has a non-empty `values` list; `all` and `any` have a non-empty list. Condition values are strings, numbers or booleans, never null. - **Constants fit their type.** A `compare` constant passes the type check of its `type` (dates in years 0001 to 9999, real days only, so `2026-02-30` is invalid). JSON Schema can't express two of these: duplicate ids, and a date pattern that names no real day. Those are checked by parsers only. `conformance/invalid/*.json` lists rule sets that every parser must reject, each with its reason. The files follow `conformance/schema/invalid-case.schema.json` (published as ). A case marked `"schemaRejects": false` passes `rules-v1.json` and is rejected by parsers only. ## Pinned behavior These rules exist because languages disagree by default. Every evaluator follows them exactly. 1. **Evaluate the wire form.** The evaluator receives the JSON value of the object, as it is or would be sent over the wire: C# evaluates the serialized JSON, Python evaluates `model_dump(mode="json", by_alias=True)`, TypeScript evaluates the parsed JSON (or the Zod-parsed output, which is the same shape). 2. **Blank** means: the key is missing, the value is `null`, the value is `""`, or the value is `[]`. Nothing else is blank: `" "`, `0`, `false` and `{}` are not blank. 3. **No type coercion.** `"1"` is not `1`. `"true"` is not `true`. A boolean is never a number (Python's `bool` is a subclass of `int`; implementations must check for it). 4. **Strict equality** (`eq`, `ne`, `in`, and `compare` with `eq`/`ne`): same JSON type and same value. Numbers compare numerically (`1` equals `1.0`). Strings compare exactly, code point by code point, with no Unicode normalization and no case folding. An array or object value is never equal to anything, so `eq` on it is false. 5. **Numbers** are compared as IEEE 754 double-precision values. `-0` equals `0`. Integers beyond 2^53 lose precision (`9007199254740993` equals `9007199254740992`), the same as in a JavaScript client, so values that need exact large integers (ids, money in minor units) SHOULD be sent as strings. 6. **Strings** in `compare` with `lt`/`le`/`gt`/`ge` are ordered by Unicode code point, not by UTF-16 code unit. (JavaScript's `<` and C#'s ordinal comparison use UTF-16 code units and disagree with code-point order for characters above U+FFFF; implementations must compensate.) 7. **`date`** is a string `YYYY-MM-DD` naming a real calendar date, years 0001 to 9999, in ASCII digits, with nothing before or after it (not even a trailing newline). Anything else fails the type check. Year `0000` is outside this range even though ISO 8601 and some libraries allow it (Zod's `z.iso.date()` accepts `0000-01-01`), so a `compare` of type `date` passes when either side is `0000-01-01`. In Zod, `isoDate()` and `isoDateTime()` from `validonce/zod` match this range. 8. **`datetime`** is a string `YYYY-MM-DDTHH:MM:SS[.fraction](Z|±HH:MM)`, with an uppercase `T` and `Z`, a real date in years 0001 to 9999, hours 00 to 23, minutes and seconds 00 to 59, and an offset whose hours are 00 to 23 and minutes 00 to 59, in ASCII digits with nothing after it. A value with no offset fails the type check. The offset `-00:00` is accepted and means UTC, like `Z`. A leap second (`:60`) fails the type check, although JSON Schema's `format: date-time` allows it. Values compare as instants in time, at **millisecond precision**: fraction digits after the third are ignored. 9. **Order and count of issues.** Rules are evaluated in array order. Each failing rule yields exactly one issue. Issues are returned in rule order. 10. **A field that is not in the data** is blank. Evaluators may assume the rule data has already been parsed as described in "Invalid rule sets". ## Issues Every failing rule produces one issue, in the same shape everywhere: client evaluation, server responses after mapping, and the conformance cases. ```json { "path": ["company"], "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {} } ``` - `path`: the rule's `path` (or its default), as a one-element array at the evaluator; hosts add prefixes for nested objects. Each element is one step into the JSON body, so a path maps to a JSON Pointer (RFC 6901) by joining the elements with `/`, after escaping `~` as `~0` and `/` as `~1`: `["items", "3", "end"]` is `/items/3/end`. - `params`: exactly the rule's `message.params`, or `{}` when it has none. Evaluators add nothing. Server responses carry the same list: FastAPI's 422 body through each error's `ctx`, and ASP.NET through a ProblemDetails extension `validonce`. The JavaScript `server-errors` adapters turn either back into this list. ## Transport (server responses) How a server reports failing rules to a client. This is a convention for implementations, not part of the rule data, so it does not change the format version. - **Shape:** an RFC 9457 problem details body (`application/problem+json`) with the issue list as a **top-level member named `validonce`**, holding the issues exactly as above. Other members (`title`, `status`, `errors`, …) are optional and free. - **Status:** 422 by default. A host may let users change it (ASP.NET: `ValidationStatusCode`). - **One response lists every failing rule**, in the order the evaluator produced them. - **Who uses it:** ASP.NET Core, and every backend added after it (Go, Spring, Fastify, NestJS). FastAPI keeps its native 422 body (the issues travel in each error's `ctx`), because FastAPI clients already read that shape. - **Clients:** `issuesFromProblemDetails` in `validonce/server-errors` reads this shape; `issuesFromResponse` reads it and FastAPI's. ```json { "type": "about:blank", "title": "One or more validation errors occurred.", "status": 422, "validonce": [ { "path": ["company"], "ruleId": "Signup.required_when.company", "key": "rules.company_required", "params": {} } ] } ``` ## Conformance cases `conformance/rules/*.json` files follow `conformance/schema/case.schema.json` (published as , so another implementation can run the same cases): ```json { "version": 1, "suite": "required_when", "cases": [ { "id": "rw-001", "description": "...", "rules": [ ... ], "data": { ... }, "expect": [ ... ] } ] } ``` `expect` is the server-side result: every rule evaluated. The client-side result is `expect` with the issues of `server_only` rules removed. Every runner checks both. Rule sets that must fail to parse are in `conformance/invalid/` (see "Invalid rule sets"). Every runner checks that its parser rejects each one, and asserts the case count. ## Using the validonce dialect `x-validonce` is also declared as a JSON Schema 2020-12 vocabulary, so tools that understand vocabularies know what the keyword is: - Vocabulary: `https://schemas.metatoy.com/validonce/vocab/rules-v1`, one keyword, `x-validonce`, whose value must validate against `rules-v1.json` and whose meaning is this document. - Vocabulary meta-schema: , the vocabulary on its own, in the usual 2020-12 layout. Both dialects include it. - Two dialects, each marking the vocabulary optional (`false`), so a validator that does not implement it still processes the schema and treats `x-validonce` as an annotation. Validating a schema against either dialect checks the shape of its rules, in nested schemas too. | Dialect | Builds on | Use it for | |---|---|---| | | OpenAPI 3.1's default dialect, `https://spec.openapis.org/oas/3.1/dialect/base` (2020-12 plus `discriminator`, `xml`, `externalDocs`, `example`) | OpenAPI 3.1 documents | | | plain JSON Schema 2020-12 | standalone JSON Schema | Using it is opt-in. In OpenAPI 3.1, point the document's `jsonSchemaDialect` at the OpenAPI dialect. `dialect-v1.json` would replace OpenAPI's default dialect, so strict tools would stop recognizing `discriminator` and the other OpenAPI keywords: ```json { "openapi": "3.1.0", "jsonSchemaDialect": "https://schemas.metatoy.com/validonce/dialect-oas31-v1.json", "components": { "schemas": { "Signup": { "type": "object", "x-validonce": { "version": 1, "rules": [] } } } } } ``` The exporters do not set it for you; the rules work the same with or without it. ## Versioning `version` is the format version. A change that could alter the result for any valid input is a new version. Adding a rule kind or condition is a new version too, because an old evaluator cannot run it; evaluators reject versions they do not know rather than skipping rules silently. ## Errata Version 1 is stable. Its published schemas (`rules-v1.json` and the files beside it on schemas.metatoy.com) change only to fix a bug, or to tighten them towards what this document already says. A valid rule never changes its result. Each such change is listed below, with a conformance case, and a rule set that newly fails to load is always one that could not have worked as written. ## Change log | Date | Change | |---|---| | 2026-11-28 | **Stable.** Conformance language and the three roles. "Invalid rule sets": closed objects, unique ids, non-empty names, and `compare` constants that must fit their `type` (`rules-v1.json` checks the constants too; 43 cases in `conformance/invalid/`). Pinned: `-0` equals `0`, integers beyond 2^53, the `-00:00` offset, leap seconds, ASCII digits only. Issue paths as JSON Pointers. OpenAPI 3.1 dialect (`dialect-oas31-v1.json`) and the vocabulary meta-schema (`meta/rules-v1.json`) | | 2026-11-24 | "Transport" (problem details with a `validonce` member). Canonical schema URLs on schemas.metatoy.com, the vocabulary and `dialect-v1.json` (validonce 0.3.3 and 0.4.0) | | 2026-11-22 | Version 1 released with validonce 0.1.0 | --- Source: https://github.com/metatoy/validonce/blob/main/docs/live-rules.md # Loading rules at runtime There are two ways for a client to get the server's rules: - **At build time:** extract them into a file (`validonce extract`) or attach them to generated Zod schemas (`validonce wrap`). Rules change when you rebuild. - **At runtime:** fetch the OpenAPI document when the page loads and read the rules from it. A rule change on the server reaches the form on the next page load, with no client release. This page covers the runtime way. Both example forms use it. ## React ```ts import { rulesFromOpenApi } from "validonce/openapi"; import type { RuleSet } from "validonce"; const [rules, setRules] = useState(null); useEffect(() => { fetch("/openapi/v1.json") // FastAPI: "/openapi.json" .then((r) => r.json()) .then((doc: unknown) => { const rs = rulesFromOpenApi(doc, "Signup"); if (!rs) throw new Error("no x-validonce rules for Signup"); setRules(rs); }); }, []); ``` Then build the form schema with `withRules(SignupSchema, rules)` once the rules arrive. The full version, with loading and error states, is [`examples/react-form/src/App.tsx`](../examples/react-form/src/App.tsx). ## Angular Fetch the document the same way (for example with `HttpClient`). For Signal Forms, build the schema with `withRules(baseSchema, rules)` once the rules arrive, as [`examples/angular-form/src/app.ts`](../examples/angular-form/src/app.ts) does. For Reactive Forms, add `validonceGroupValidator(rules)` to the form group. ## Things to know - **Schema names.** `rulesFromOpenApi(doc, "Signup")` also finds `Signup-Input`, the name FastAPI gives a model's request schema. - **Serve the document to your clients.** ASP.NET Core serves it at `/openapi/v1.json` with `MapOpenApi()`, FastAPI at `/openapi.json`. If you disable the document in production, use the build-time way instead. - **Fail closed or open, deliberately.** If the fetch fails, the examples show an error and no form. Showing the form without rules is also safe, because the server still enforces every rule and answers 422. Users just see the error later. - **Caching.** The document is a normal HTTP resource. Let your usual cache headers decide how quickly a rule change reaches clients. - **Size.** You download the whole OpenAPI document. For large APIs, the build-time way gives a smaller bundle. --- Source: https://github.com/metatoy/validonce/blob/main/docs/kubernetes.md # Kubernetes custom resources > **Try it first:** [the playground with a Kubernetes CRD](https://playground.metatoy.com/?backend=k8s&frontend=react) translates a CRD's CEL rules in the browser (the server step is simulated). Kubernetes custom resource definitions (CRDs) carry cross-field rules in their OpenAPI schemas, under `x-kubernetes-validations`. The rules are written in CEL (`self.maxReplicas >= self.minReplicas`), and only the API server enforces them. A console that edits these resources has no rules in the browser: users submit, get rejected, and read the server's message. validonce translates the CEL rules that match its five rule kinds into `x-validonce`. Every validonce frontend then enforces them instantly, with no hand-written client rules. Rules it cannot translate are kept as `server_only`, and a dry run asks the API server about them. ## What you get - Rules that match a validonce kind run in the browser, and the user sees the same message Kubernetes would send. - Everything else still reaches the API server. Nothing is dropped. - The result is a normal OpenAPI document with `x-validonce`, so the same rules feed the form libraries and the generator plugins. ## In the browser, from `/openapi/v3` The API server serves the schemas of each group and version at `/openapi/v3/apis//`. Fetch the document with the console's existing client and translate it: ```ts import { rulesAt, translateKubernetesOpenApi } from "validonce/kubernetes"; const doc = await client.get("/openapi/v3/apis/example.test/v1"); const { doc: augmented, catalog, report } = translateKubernetesOpenApi(doc); const rules = rulesAt(augmented, "test.example.v1.Signup", "/properties/spec"); ``` Then build the form as in [Loading rules at runtime](live-rules.md): `withRules(baseSchema, rules, { messages: catalog })`. Rules sit on the schema node that carries `x-kubernetes-validations`, so a rule on `spec` gives a `RuleSet` for the `spec` fields. Adding the `spec.` prefix is the form's job. ## At build time: `validonce k8s` ```sh kubectl get crd signups.example.test -o json | validonce k8s - --out signup.openapi.json --catalog messages.json --report ``` The input is a CRD manifest or a Kubernetes OpenAPI v3 document, as JSON (convert YAML first). For a CRD, the output is an OpenAPI 3.1 document with one component schema per version (`Signup`, or `Signup_v1` when there are several). For an OpenAPI document, it is the same document. Either way, `x-validonce` sits next to each `x-kubernetes-validations`, and `--catalog` writes the message catalog (each rule's CEL `message`). `--report` prints, for each rule, whether it was translated or kept as `server_only`, and why. Use this path for a smaller bundle, or to feed the generator plugins. ## What cannot be translated: the dry run Rules with arithmetic, string functions, list macros, or `oldSelf` stay on the server. To show their errors on the right fields, send the resource to the API server with `dryRun=All`. It validates the object and stores nothing. ```ts import { dryRunIssues, dryRunUrl, k8sServerCatalog, } from "validonce/kubernetes"; // the helpers live in js/src/kubernetes-dryrun.ts for now import { fieldErrorsFromIssues } from "validonce/server-errors"; const res = await client.post(dryRunUrl(`/apis/example.test/v1/namespaces/${ns}/signups`), body); if (res.status === 422) { const issues = dryRunIssues(await res.json(), { root: "spec" }); const errors = fieldErrorsFromIssues(issues, { ...catalog, ...k8sServerCatalog }); // errors: { company: "Company must be 40 characters or fewer" } } ``` - `dryRunUrl(url)` adds `dryRun=All` to a resource URL. No Kubernetes client is bundled. - `dryRunIssues(status, { root })` turns a `Status` failure (`reason: Invalid`, `code: 422`, `details.causes[]`) into issues. Each cause's `field` (`spec.end`, `spec.items[2].end`) becomes a path relative to `root` (default `spec`, so `["items", "2", "end"]`). - Each issue has `ruleId` and `key` `k8s.server`, and `params: { message, reason }`. Add `k8sServerCatalog` to your catalog and the user sees the text the server wrote, without Kubernetes' `Invalid value: ...:` prefix. - A CEL rule with `fieldPath` lands on that field. A rule without one is reported on the object that carries it (`spec`), which gives an empty path: show it as a form-level error. - Any other body, such as a 403 or a non-`Status` answer, returns no issues. The API server also catches schema errors (a wrong enum value, a missing required field), and these come back the same way, so the dry run is useful for more than `server_only` rules. ## Translation table These are checked against the API server's own CRD validation code: `apiextensions-apiserver` with prune, defaults, schema validation, then CEL. CI runs every translated rule against Kubernetes' verdicts on the same inputs (the `k8s-cel-diff` job, fixtures in `conformance/kubernetes/`), and fails if validonce would ever block an object Kubernetes accepts. A rule is translated only when its **guard** holds; otherwise it is kept as `server_only` with the reason in the report. | CEL shape (and its mirror forms) | validonce | Guard | |---|---|---| | `!(cond) \|\| has(self.f)`, `cond ? has(self.f) : true` | `required_when` | G-blank on `f` and on fields tested with `has()`; G-key on fields compared with `==`, `!=`, `in`; no `default` on fields read for presence | | `&&` `\|\|` `!` in a condition | `all` / `any` / `not` | none | | `self.x == lit`, `!= lit`, `in [lits]` | `eq` / `ne` / `in` | G-key; the literal's type equals the field's type | | `self.a self.b`, `self.a lit` on numbers | `compare` (number) | G-missing; integers need `format: int32` or `minimum` and `maximum` within ±2^53; mixed int and double only for `<` `<=` `>` `>=` | | the same on strings | `compare` (string) | G-missing and G-blank on every operand | | fields with `format: date` | `compare` (date) | G-missing | | fields with `format: date-time`, with or without `timestamp()` | `compare` (datetime) | G-missing; a `pattern` limiting fractional seconds to 3 digits | | `has(self.a) \|\| has(self.b) \|\| …` | `at_least_one_of` | G-blank on every member | | `[has(..), ..].exists_one(x, x)`, `(has(a) ? 1 : 0) + … == 1` | `exactly_one_of` | G-blank on every member | | `has(self.a) == has(self.b)`, `(has(a) && has(b)) \|\| (!has(a) && !has(b))` | `all_or_none` | G-blank on every member | | `timestamp()` on a string without `format`; arithmetic; string functions; macros; `oldSelf`; `self.a.b` | not translated | kept as `server_only`, or only reported | **Guards:** - **G-blank:** the field can't hold `""` or `[]`. That means a string with `minLength` ≥ 1, a `format` of `date` or `date-time`, or an `enum` without `""`; an array with `minItems` ≥ 1; or another type. - **G-key:** the field is `required`, has a `default`, or the rule itself guards it with `has()`. Kubernetes errors when a rule reads a missing field. - **G-missing:** both sides of a comparison are `required`, or the rule is written `!has(self.a) || !has(self.b) || self.a >= self.b`. This is the usual form, and it means exactly what validonce's compare does: skip when a side is missing. ### Why the guards - **`has()` versus blank.** CEL's `has()` is false for a missing field and for an explicit `null`, as validonce's blank is. It differs only on `""` and `[]`, which CEL counts as present. G-blank rules those out. - **Defaults** are applied before CEL runs, so a defaulted field is never absent on the server. The browser can't know that. - **Precision.** CEL compares timestamps to the nanosecond, validonce to the millisecond. That is why date-time compares need a pattern limiting the fraction to 3 digits. - **Large integers.** Integers beyond 2^53 are exact in CEL and approximate in JavaScript. - **Strings** compare by code point in both, including case, U+FFFF versus U+10000, and unnormalised text. **Write translatable CRDs:** give text fields `minLength: 1`, give integers `format: int32` (or `minimum` and `maximum`), give date-time fields a pattern limiting fractions to milliseconds, and guard comparisons with `has()`. Run `validonce k8s --report` to see which rules translate and why the rest don't. ## Migrate with an agent An agent can translate a CRD for you without rewriting its CEL: the `translate_kubernetes` tool takes a CRD manifest or a Kubernetes OpenAPI v3 document and returns the augmented document, the message catalog and a per-rule report (`translated`, or `server_only` with the reason). The skill's [Kubernetes guide](../skills/validonce-migrate/references/kubernetes.md) has the steps, and `suggest_client_wiring` returns the client set-up. These need `validonce-mcp` 0.2.0 or later. See [Migrating with an agent](agentic-migration.md). ## Example [`examples/k8s-form`](../examples/k8s-form) is a React form for a sample `Signup` CRD ([`crd/signup-crd.yaml`](../examples/k8s-form/crd/signup-crd.yaml)). Four of its rules run in the browser. The fifth (`self.company.size() <= 40`) is answered by a recorded Kubernetes 422 through `dryRunIssues`, so the example needs no cluster. --- Source: https://github.com/metatoy/validonce/blob/main/docs/agentic-migration.md # Migrating an existing project with an agent Moving an existing project to validonce means finding every hand-written cross-field check, deciding which rule kind each one is, rewriting it once on the server, deleting the client copies, and checking that nothing changed on generated inputs. A coding agent can do most of that with two pieces from this repo: - **`validonce-mcp`**: an MCP server with deterministic tools that read, check, evaluate, generate and compare rules. - **`validonce-migrate`**: an agent skill with the steps and the per-library mapping guides. The agent proposes the change and you review the diff. Nothing is committed for you. ## Install **Claude Code (plugin: the skill and the server together):** ```text /plugin marketplace add metatoy/validonce /plugin install validonce@validonce ``` **The server alone, in any MCP client:** ```text claude mcp add --transport stdio validonce -- npx -y validonce-mcp ``` ### VS Code and GitHub Copilot One click: [Install in VS Code](vscode:mcp/install?%7B%22name%22%3A%22validonce%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22validonce-mcp%22%5D%7D) (opens VS Code and asks you to confirm). Or add `.vscode/mcp.json` to the project: ```json { "servers": { "validonce": { "type": "stdio", "command": "npx", "args": ["-y", "validonce-mcp"] } } } ``` Then pick **Agent** mode in Copilot Chat and enable the `validonce` tools. Workspace folders are passed to the server as its roots. ### Cursor Add `.cursor/mcp.json` (or `~/.cursor/mcp.json` for every project): ```json { "mcpServers": { "validonce": { "command": "npx", "args": ["-y", "validonce-mcp"] } } } ``` ### Any other MCP client (generic stdio) Run `npx -y validonce-mcp` as a stdio server (Node 20 or later). The command is `npx`, the arguments are `-y validonce-mcp`, and there is nothing to configure: it needs no network, no API key and no environment variables. A client that sends no workspace roots gets the directory the server was started in. The server works with any MCP client. For other agents that read Agent Skills, copy `skills/validonce-migrate/` into the folder your agent reads skills from, and add the server with your agent's MCP configuration. We only claim **support** for agents that pass the graded evals (see "What has been tested" below); the configurations above are "works with any MCP client", not a support claim. ## What happens 1. **Inventory.** The agent finds cross-field checks: FluentValidation `When`/`Must`/`GreaterThanOrEqualTo(x => x.Other)`, Pydantic `@model_validator`, Zod `refine`/`superRefine`, Angular group validators, yup `.when`/`.test`, go-playground/validator tags, Jakarta Bean Validation, class-validator, Joi `.when`/`.custom`, VeeValidate. Kubernetes CRDs with CEL (`x-kubernetes-validations`) take a separate path: `translate_kubernetes` translates them and leaves the CEL as it is. 2. **Classify.** Each check becomes one of the five rule kinds, or stays hand-written with a one-line reason. Arithmetic between fields, a format that depends on another field, async or database checks, rules on nested objects, and comparisons that rely on type coercion stay hand-written. 3. **Propose and check.** The agent writes the rules and runs `check_rules` against your OpenAPI schema (field names, types, duplicate ids). 4. **Generate.** `generate_code` writes the server code for the target you pick: C# (`ValidonceValidator`), Python (`ValidonceModel`), Go (`validonce.MustBuild`), Java (a `RuleDefinition` with `@ValidonceRules`) or TypeScript (`defineRules` with a Fastify or NestJS schema), and the client wiring (`withRules`, react-hook-form, Angular, Vue, plain HTML). `suggest_client_wiring` returns the set-up for React, Angular, Vue or plain HTML, including the kubb, Hey API and orval plugin configs, the dependent-field helpers and the server-error mapping. The Go, Java, TypeScript, Vue and plain HTML targets, `translate_kubernetes` and `suggest_client_wiring` need `validonce-mcp` 0.2.0 or later. 5. **Prove.** `generate_inputs` creates test inputs biased toward the edges the rules care about: every combination of blank and filled fields, equal values, ±1, date edges and time-zone offsets. With your consent, the agent runs your **old** validator on them with a runner script (scripts in `skills/validonce-migrate/scripts/`; the sandbox each one has is listed under Safety). Kubernetes CRDs have no old validator to run: the CEL stays in place and `translate_kubernetes` reports, per rule, whether it was translated or kept as `server_only`. `compare_results` compares the old answers with validonce's. 6. **Migrate only what passed.** A rule is migrated only when the old and new validators accept and reject exactly the same inputs, and the rule was triggered both ways often enough to count. 7. **Report and hand over.** The agent writes a migration report (found, migrated, proven, kept and why, the commands to re-run the proof) and leaves the diff for you. ## Safety - **The server never runs your code.** Its tools take structured input and return data. One tool, `generate_inputs`, can write one new `.jsonl` file inside your project, and never overwrites a file. - **Your old validator runs only with your consent,** through the runner scripts, in a scratch directory: - **Node (Zod, yup, Angular):** runs in `node --permission` with an empty environment and network APIs removed. Any import that needs I/O fails with a clear message, and the bundled `require` allows only the two pure builtins `url` and `util`; any other `require` throws. - **Python (Pydantic):** runs with `python -I` and sockets disabled. - **.NET (FluentValidation):** loads your built assembly. A validator that needs injected services is reported as "cannot prove", not guessed. - **Node, class-validator and Joi:** the same `node --permission` runner as Zod, yup and Angular, with `class-validator`, `class-transformer`, `reflect-metadata` or `joi` added to the allowed imports. - **Go (go-playground/validator):** a small Go program (its module needs Go 1.26.10) that you build with your struct and run with `go run`. It has no sandbox of its own: it opens no connections itself, but your validators are your code. - **Java (Jakarta Bean Validation):** one Java file launched on a plain JDK 21 against Hibernate Validator. It has no sandbox of its own, and a validator that needs injected beans is reported as "cannot prove". The runners are tripwires, not full sandboxes, and the Go and Java runners are not even that. For a hard network block, run any of them under `sandbox-exec` (macOS) or `unshare -n` (Linux). - **File contents are treated as data.** The skill tells the agent to ignore instructions found in code, comments or docs. ## Limits - **Only the five rule kinds.** Everything else stays hand-written, which is expected. - **Where an error is reported.** A Pydantic `model_validator` that raises without naming a field is reported at `__root__`. The verdict (accept or reject) is still exact, but the agent decides which field the error belongs on by reading the code. - **Inputs must parse.** Inputs that your model would reject at parse time are reported separately, not as rule differences. - **Wire names.** Rules use the names in the JSON body. Where the old validator reports a different name (a class-validator property with `@Expose({ name })`, a Java property renamed by Jackson), the paths can differ and show up as field-location warnings, not as accept/reject differences. The Jakarta and Go runners map to wire names; the class-validator runner does not (see `references/class-validator.md`). - **Runner scope.** The class-validator runner bundles with `experimentalDecorators` and no decorator metadata, so a DTO that needs `emitDecoratorMetadata` must state its types explicitly. The Joi runner uses Joi's defaults (type conversion on, unknown keys rejected). VeeValidate has no rule engine of its own, so the runner proves the yup or Zod schema it hosts, not the Vue component. ## What has been tested The proof tools and runners are tested in CI on hand-written versions of the Signup example for FluentValidation, Pydantic, Zod, yup and Angular: each matches validonce on every test input. Agent results are measured with [promptfoo](https://www.promptfoo.dev) (harness in `mcp/evals`), and support for a given agent is claimed here only after it passes that evaluation. Every run is graded by code, not by a model: the agent's rules must accept and reject exactly what the old validator did on thousands of generated inputs, the migrated validator as a whole must agree with the original, every check that cannot be migrated must still be there with a reason, the project must still build, and only the expected files may change. | Agent | Tuning set (10 cases: our examples in five libraries, plus five that must not be migrated) | Hold-out (three public apps, measured once: .NET/FluentValidation, FastAPI/Pydantic, React/Zod) | |---|---|---| | Claude Code (Opus) | 30 of 30 runs pass every check | 6 of 9 pass every check; the other 3 migrated less than they could (rules left hand-written, with reasons) | | GitHub Copilot CLI (GPT-5.3-Codex) | 7 of 7 | 2 of 3; one left code that did not import (caught by the build check) | Of 49 graded runs (final tuning round and hold-out), 45 passed every check (43 as first run; two rescored after a timeout and a build failure), and in those the old and migrated validators agreed on every generated input. In a later check with other inputs, 9 of the 28 passing runs that migrated rules changed a verdict on at least one, mostly dates held as plain text. Supported: **Claude Code**. Copilot's results are reported as measured. ### Go, Java, NestJS, Joi, Vue and Kubernetes The newer sources were graded later, the same way, with Claude Code. Copilot has not been measured on them yet. | Agent | Tuning set (10 cases: go-playground, Jakarta, class-validator, Joi, VeeValidate and a Kubernetes CRD, plus four that must not be migrated) | Date cases (yup, Angular, NestJS and Joi with dates checked at runtime; the proof includes malformed and partial dates) | Hold-out (one public Vue/VeeValidate app, measured once) | |---|---|---|---| | Claude Code (Opus) | 18 of 20 pass every check; both misses are Joi runs that kept a date rule hand-written | 6 of 7; the miss migrated correctly but added a file it was not asked for | 1 of 1 | | Claude Code (Sonnet) | not run | 4 of 4 (one run per case) | not measured | In the passing tuning runs the old and migrated validators agreed on every generated input. In a later check with other inputs, 11 of the 13 passing runs that migrated rules changed a verdict on at least one, mostly malformed or partial dates in the NestJS and Vue cases, and years 0000 or above 9999 in Go and Spring. The date cases put such inputs in the proof itself, and none of their passing runs changed a verdict. --- Source: https://github.com/metatoy/validonce/blob/main/docs/comparison.md # How validonce compares validonce covers one narrow job: **cross-field rules** (a field required when another has a value, one date after another, at least one of a group, and so on). They are written once on the server (ASP.NET Core, FastAPI, Fastify, NestJS, Go, Spring Boot, or the CEL rules of a Kubernetes CRD) and enforced in the browser from the OpenAPI document. Here is how that compares with the alternatives. ## Writing the rules twice The usual approach: a FluentValidation or Pydantic rule on the server, and a hand-written Zod `refine`/`superRefine` (or an Angular group validator) on the client. - **Works with no new dependency.** For one or two rules, this is fine. - **The two copies drift.** Nothing checks that the client copy matches the server. Small differences are easy to miss: `>` against `>=`, whether `""` counts as missing, how dates compare. validonce pins these in [rule-format-v1.md](rule-format-v1.md) and checks every evaluator against the same [conformance cases](../conformance/rules/). - **Changing a rule means changing two codebases.** With validonce, the client reads the rule from the server's OpenAPI document, so a server change reaches the client on the next build (or the next page load, see [live-rules.md](live-rules.md)). ## OpenAPI-to-Zod generators alone (orval, kubb) [orval](https://github.com/orval-labs/orval) and [kubb](https://github.com/kubb-labs/kubb) (both MIT) generate Zod schemas from an OpenAPI document. - **They carry field rules**: type, required, length, enum, `pattern`, because those are standard JSON Schema keywords. - **They do not carry cross-field rules.** JSON Schema has no keyword for "required when another field equals X" or "end after start", so there is nothing in the document for a generator to translate. - **validonce adds the missing part and works with them**: `validonce wrap` attaches the server's `x-validonce` rules to the schemas they generate. See [client-react.md](client-react.md). ## protovalidate [protovalidate](https://github.com/bufbuild/protovalidate) (Apache-2.0, from Buf) is the mature project in this space, and the closest in idea: rules defined once, enforced in several languages. - **It is much broader.** Rules are written as [CEL](https://cel.dev) expressions, so they can express arbitrary logic, including the cross-field rules validonce covers and many it cannot. It has implementations for Go, Java, Python, C++ and JS/TS (per its repository description). - **Its source of truth is Protobuf.** Rules are annotations on `.proto` messages. If your API is described in Protobuf, use protovalidate. - **validonce starts from where many web teams already are**: request models in ASP.NET Core or FastAPI, an OpenAPI document generated from them, and Zod forms. There is no schema language to adopt, and rules stay in FluentValidation or Pydantic. ## valbridge [valbridge](https://github.com/vectorfy-co/valbridge) bridged Zod and Pydantic with conversion and code generation. Its repository was **archived** (read-only), with its last push on 2026-11-03. As we read it before archiving, it covered field rules and did not support custom (cross-field) validators. ## Migrating existing checks Moving hand-written checks to a shared rule format is usually a manual job. validonce ships an MCP server (`validonce-mcp`) and an agent skill that read the checks in FluentValidation, Pydantic, Zod, yup, Angular, go-playground/validator, Jakarta Bean Validation, class-validator, Joi and VeeValidate, translate Kubernetes CEL, and compare the old validator with validonce on generated inputs. The agent proposes the change and you review the diff. See [agentic-migration.md](agentic-migration.md). ## What validonce does not do - **Arbitrary logic.** There are five rule kinds and no expression language. Arithmetic between fields (`a + b == total`), a format that depends on another field, and rules across nested objects stay hand-written. A rule marked `server_only` runs on the server and is skipped by clients. - **Async or database checks** (uniqueness, "user exists"). These belong on the server only. - **Field-level rules.** Type, length, enum and `pattern` travel as standard JSON Schema keywords; validonce only lints `pattern` regexes for portability. - **Other stacks, for now.** Servers: ASP.NET Core, FastAPI, Fastify, NestJS, Go (Huma) and Spring Boot. Clients: Zod 4 (with react-hook-form, Angular Signal Forms or VeeValidate), Angular Reactive Forms, and plain HTML or web components. - **Messages.** The rule carries a message key and parameters, not text. Your app maps keys to text. --- Source: https://github.com/metatoy/validonce/blob/main/docs/regex-findings.md # Regex portability findings Engines: js (`new RegExp(p)`), js-u (`u` flag), python-re, rust-regex (Pydantic default), dotnet. All use search semantics. Expectations were measured with Node 22, Python 3.14, Pydantic 2.14 and .NET 11. Python-version-dependent cases: `\z` (3.14+), possessive quantifiers and atomic groups (3.11+), inline flags not at the start (error from 3.11). Scoped modifiers `(?i:...)` are left out because JavaScript support depends on the Node version. | ID | Severity | Title | What differs | Portable rewrite | Cases | |---|---|---|---|---|---| | VR001 | error | \w matches non-ASCII letters in some engines | \w is ASCII-only in JavaScript but matches accented and CJK letters in Python, Rust and .NET. | `[A-Za-z0-9_]` | rx-001 | | VR002 | error | \d matches non-ASCII digits in some engines | \d is 0-9 only in JavaScript but also matches Arabic-Indic and fullwidth digits in Python, Rust and .NET. | `[0-9]` | rx-002 | | VR003 | warning | \s covers different white-space characters | The set of characters \s matches differs between engines: U+FEFF only in JavaScript, U+001C only in Python, U+0085 and U+00A0 not in every engine. | `[ \t\r\n\f\v]` | rx-003 | | VR004 | warning | \b word boundary differs next to accented letters | Because \w differs, \b finds a boundary between "f" and "é" in JavaScript but not in Python, Rust or .NET. | `(?![A-Za-z0-9_]) or (?...) is Python and Rust (also (?...) in Rust); (?...) is JavaScript and .NET; (?P=n) and \k backreferences are not shared. | `Use a plain capturing group (...) when the name is not needed` | rx-024, rx-025, rx-026, rx-027 | | VR012 | error | Possessive quantifiers and atomic groups are not portable | a++ is accepted by Python 3.11+ and (as a plain repeat) Rust, but not by JavaScript or .NET; (?>...) is accepted by Python 3.11+ and .NET only. | `Rewrite without them (plain greedy quantifier)` | rx-028, rx-029 | | VR013 | error | Inline flags are not portable | (?i) at the start is an error in JavaScript; in the middle it is also an error in Python 3.11+. | `Spell out both cases in a class, e.g. [Aa][Bb][Cc]` | rx-030, rx-031 | | VR014 | warning | . matches line terminators differently | . rejects \r and U+2028 in JavaScript but accepts them in Python, Rust and .NET; all reject \n. | none (a negated class still differs on astral characters, see VR015) | rx-016 | | VR015 | warning | . and characters outside the BMP | "😀" is one character to . in js-u, Python and Rust but two in plain JavaScript and .NET (UTF-16 surrogate pairs), so length rules like ^.{1,10}$ differ. | none | rx-017, rx-018 | | VR016 | error | [^] is only valid in JavaScript | [^] means any character in JavaScript and is an error elsewhere. | `[\s\S]` | rx-005 | | VR017 | error | \p{L} Unicode properties are not portable | \p{L} works in js-u, Rust and .NET, is a literal "p{L}" in plain JavaScript, and is an error in Python re. | none | rx-006 | | VR018 | warning | {,3} quantifier is read differently | {,3} means 0 to 3 in Python, is literal text in JavaScript and .NET, and an error in js-u and Rust. | `{0,3}` | rx-034 | | VR019 | error | Unicode escape forms differ | \x{...}, \U00000000 and \u{...} are each accepted by only some engines; \uXXXX is accepted by all. | `the literal character, or \uXXXX (surrogate pairs for non-BMP)` | rx-037, rx-038, rx-039, rx-040 | | VR020 | error | Class subtraction and intersection syntax differ | [a-z-[aeiou]] is .NET, [[a-z]&&[^aeiou]] is Rust, and js-u rejects both (only the v flag adds set operations, and js-u is not v). | `[bcdfghjklmnpqrstvwxyz]` | rx-007, rx-008, rx-009 | | VR021 | warning | Case-insensitive matching of special letters differs | With (?i), the Kelvin sign K matches k in Python, Rust and .NET; the long s matches s in Python and Rust but not .NET; JavaScript rejects (?i). | `[Kk], [Ss]` | rx-032, rx-033 | | VR022 | error | Shorthand class as a range endpoint | [\w-.] works in JavaScript and .NET but is an error in js-u, Python and Rust. | `[\w.-] (put the hyphen last)` | rx-010 | | VR023 | error | POSIX bracket classes [[:alpha:]] | [[:alpha:]] is a class only in Rust; elsewhere it is an ordinary class followed by stray characters (and js-u rejects it). | `[A-Za-z]` | rx-011 | | VR025 | error | Literal { and ] are not portable | An unterminated {2 and a lone ] are accepted by most engines but rejected by js-u (and { by Rust). | `\{ and \]` | rx-035, rx-036 | | VR026 | error | Unnecessary escapes are rejected by some engines | \@ \_ \- are identity escapes: fine in JavaScript, Python and Rust, errors in js-u (and \_ in .NET). | `drop the backslash (put - last in a class)` | rx-041, rx-042 | ## Per-engine behavior ### VR001 \w matches non-ASCII letters in some engines - **js**: ASCII only [A-Za-z0-9_] - **js-u**: ASCII only (the u flag does not widen \w) - **python-re**: Unicode letters, digits, underscore - **rust-regex**: Unicode letters, digits, underscore - **dotnet**: Unicode letters, digits, underscore ### VR002 \d matches non-ASCII digits in some engines - **js**: 0-9 only - **js-u**: 0-9 only - **python-re**: any Unicode decimal digit - **rust-regex**: any Unicode decimal digit - **dotnet**: any Unicode decimal digit ### VR003 \s covers different white-space characters - **js**: includes U+00A0, U+FEFF, U+2003, U+2028; not U+0085 - **js-u**: same as js - **python-re**: includes U+001C and U+0085; not U+FEFF - **rust-regex**: Unicode White_Space: includes U+0085, not U+FEFF or U+001C - **dotnet**: includes U+0085, U+00A0; not U+FEFF or U+001C ### VR004 \b word boundary differs next to accented letters - **js**: ASCII word characters - **js-u**: ASCII word characters - **python-re**: Unicode word characters - **rust-regex**: Unicode word characters - **dotnet**: Unicode word characters ### VR005 $ matches before a final newline in Python and .NET - **js**: $ is end of input only - **js-u**: $ is end of input only - **python-re**: $ also matches before a final \n - **rust-regex**: $ is end of input only - **dotnet**: $ also matches before a final \n ### VR006 \Z and \z are not portable - **js**: identity escape: matches the letter Z or z - **js-u**: error - **python-re**: \Z is absolute end; \z accepted only from Python 3.14 (error before) - **rust-regex**: \z is end of input; \Z is an error - **dotnet**: \Z end or before final \n; \z absolute end ### VR007 \A is not portable - **js**: identity escape: matches the letter A - **js-u**: error - **python-re**: start of input - **rust-regex**: start of input - **dotnet**: start of input ### VR008 Lookbehind support and width rules differ - **js**: supported, variable width allowed - **js-u**: supported, variable width allowed - **python-re**: fixed width only - **rust-regex**: not supported (error) - **dotnet**: supported, variable width allowed ### VR009 Lookahead is rejected by Rust regex - **js**: supported - **js-u**: supported - **python-re**: supported - **rust-regex**: not supported (error) - **dotnet**: supported ### VR010 Backreferences are rejected by Rust regex - **js**: supported - **js-u**: supported - **python-re**: supported - **rust-regex**: not supported (error) - **dotnet**: supported ### VR011 Named group syntax differs - **js**: (?) and \k only - **js-u**: (?) and \k only - **python-re**: (?P) and (?P=n) only - **rust-regex**: (?P) and (?); no backreferences - **dotnet**: (?) and \k; (?P) is an error ### VR012 Possessive quantifiers and atomic groups are not portable - **js**: error - **js-u**: error - **python-re**: both supported (3.11+) - **rust-regex**: a++ accepted (as a nested repeat, not possessive); (?>...) error - **dotnet**: (?>...) supported; a++ error (nested quantifier) ### VR013 Inline flags are not portable - **js**: error - **js-u**: error - **python-re**: only at the very start - **rust-regex**: supported anywhere - **dotnet**: supported anywhere ### VR014 . matches line terminators differently - **js**: excludes \n \r U+2028 U+2029; U+0085 is matched - **js-u**: excludes \n \r U+2028 U+2029; U+0085 is matched - **python-re**: excludes \n only - **rust-regex**: excludes \n only - **dotnet**: excludes \n only ### VR015 . and characters outside the BMP - **js**: two code units: ^.$ fails - **js-u**: one code point - **python-re**: one code point - **rust-regex**: one code point - **dotnet**: two UTF-16 units: ^.$ fails ### VR016 [^] is only valid in JavaScript - **js**: matches any character - **js-u**: matches any character - **python-re**: error - **rust-regex**: error - **dotnet**: error ### VR017 \p{L} Unicode properties are not portable - **js**: literal p{L} - **js-u**: Unicode property - **python-re**: error - **rust-regex**: Unicode property - **dotnet**: Unicode property ### VR018 {,3} quantifier is read differently - **js**: literal text - **js-u**: error - **python-re**: 0 to 3 repeats - **rust-regex**: error - **dotnet**: literal text ### VR019 Unicode escape forms differ - **js**: \uXXXX; \u{} only with u flag - **js-u**: \uXXXX and \u{...} - **python-re**: \uXXXX and \UXXXXXXXX - **rust-regex**: \x{...}, \u{...}, \uXXXX, \UXXXXXXXX - **dotnet**: \uXXXX only ### VR020 Class subtraction and intersection syntax differ - **js**: literal characters, no set operations - **js-u**: error - **python-re**: literal characters, no set operations - **rust-regex**: && intersection, -- difference, nested classes - **dotnet**: subtraction with -[...] and --[...]; no && intersection ### VR021 Case-insensitive matching of special letters differs - **js**: error - **js-u**: error - **python-re**: full Unicode case folding - **rust-regex**: full Unicode case folding - **dotnet**: Kelvin yes, long s no ### VR022 Shorthand class as a range endpoint - **js**: hyphen is literal - **js-u**: error - **python-re**: error - **rust-regex**: error - **dotnet**: hyphen is literal ### VR023 POSIX bracket classes [[:alpha:]] - **js**: nested set read as [[:alph] then literal - **js-u**: error - **python-re**: same as js - **rust-regex**: letters - **dotnet**: same as js ### VR025 Literal { and ] are not portable - **js**: literal - **js-u**: error - **python-re**: literal - **rust-regex**: { error; ] literal - **dotnet**: literal ### VR026 Unnecessary escapes are rejected by some engines - **js**: accepted - **js-u**: only syntax characters may be escaped - **python-re**: accepted - **rust-regex**: accepted - **dotnet**: \_ is an error --- Source: https://github.com/metatoy/validonce/blob/main/docs/releasing.md # Releasing How the packages are published. Every package publishes from a GitHub Actions workflow when a GitHub Release is published. npm, NuGet and PyPI use trusted publishing (OIDC), so no tokens are stored. Maven Central has no trusted publishing, so `publish-maven.yml` uses secrets in a protected environment. The Go module is published by a tag, which `publish-go.yml` pushes. ## Order 1. `node scripts/prepare-release.mjs X.Y.Z` sets the version everywhere (C#, TypeScript, Python, Java, the demo chart, the bug-report template) and turns the CHANGELOG's "## Unreleased" into the release heading. Open the release PR and merge it. 2. Publish the GitHub Release `vX.Y.Z` from `main`. This runs the npm, NuGet and PyPI workflows, which check the tag against the version and attach attested packages to the Release. 3. Go: nothing to do. `publish-go.yml` runs on the same Release: it tests the module, pushes `go/vX.Y.Z` on the Release's commit and fetches it through the Go module proxy. (For an older release, run it by hand with the release tag.) 4. Maven Central: `publish-maven.yml` runs on the same Release once you approve the deployment (see below). 5. Docs site, for a minor release (X.Y.0): freeze its docs with `node website/scripts/snapshot.mjs X.Y vX.Y.0` (after the tag exists), then open a PR with `website/versioned_docs/`, `website/versioned_sidebars/`, `website/versions.json` and `website/version-refs.json`. Once merged, validonce.metatoy.com shows X.Y as the default version and `main` stays under "Next". A patch release needs nothing unless a docs fix should reach the frozen copy. ## Maven Central Two artifacts, `com.metatoy:validonce-core` and `com.metatoy:validonce-spring`, built from `java/` (Gradle, JDK 21). The version is `version` in `java/gradle.properties` (set by `prepare-release.mjs`). `publish-maven.yml` publishes them when the GitHub Release is published. Maven Central has no token-free trusted publishing, so the job reads secrets from the protected **`maven-central`** environment. It is limited to `v*` tags and needs the founder's approval on every run: open the run and press "Review deployments". The job: 1. Checks the tag against `java/gradle.properties` and runs `./gradlew check`. 2. Builds the signed bundle (`./gradlew centralBundle -Pvalidonce.sign`), signing in memory with the CI signing key. 3. Attests it and uploads it to the Central Portal API with `publishingType=AUTOMATIC`, then waits until it is `PUBLISHED`. 4. Attaches the bundle to the Release. For an older release, run it by hand with the release tag. CI's `java` job builds a signed bundle with a throwaway key on every push, so the signing path is tested without the secrets. **Secrets** (environment `maven-central`, set once): | Secret | What | |---|---| | `MAVEN_SIGNING_KEY` | ASCII-armored secret key of the **CI signing key** (`validonce CI `, ed25519, signing only, 2-year expiry). It is not the founder's personal key. Fingerprint `E99C AF89 14E0 7E01 A9E9 8782 2CC3 5EBA 34E4 BF91`, expires 2028-11-23. Its public key is on keyserver.ubuntu.com and keys.openpgp.org. | | `MAVEN_SIGNING_PASSWORD` | Its passphrase | | `MAVEN_CENTRAL_USERNAME`, `MAVEN_CENTRAL_PASSWORD` | A Central Portal **user token** (central.sonatype.com, Account, Generate User Token), not the account login | To rotate either secret: make a new key or token, update the secret, then revoke the old key (publish its revocation) or the old token. **Manual fallback** (founder's Mac, signed with the local gpg agent): `cd java && ./gradlew centralBundle -Pvalidonce.sign`, then upload `build/central/validonce--bundle.zip` at ("Publish Component"). A published version can't be changed or removed.