Writing · C# Advent 2026

Stop writing your FluentValidation rules twice

Write the rule once in ASP.NET Core. Your React form enforces the same rule, and catches up on its own when the rule changes.

This post is part of the 2026 C# Advent calendar: two C# posts a day, December 1 to 25. Thanks to the organizers for putting it together.

I saw this problem first-hand in my 11 years at BuzzFeed: the same form validation written once in the backend and again in the frontend, and the two copies slowly drifting apart. Sharing one set of rules is the kind of fix every team agrees would be nice and nobody gets to. It stuck with me. I wanted to fix it not only for my future self, but to take a pass at solving it and share the result with the open-source community.

Some form validation travels well. A required field, a maximum length or a pattern lands in your OpenAPI document as JSON Schema, and client generators turn it into frontend checks for free.

Form validation that depends on more than one field doesn’t travel at all. For example:

In FluentValidation that’s a When or a GreaterThanOrEqualTo(x => x.Other), and JSON Schema has no good way to say it. So the frontend writes it again:

C#
RuleFor(x => x.Company).NotEmpty().When(x => x.Plan == "pro");RuleFor(x => x.End).GreaterThanOrEqualTo(x => x.Start).When(x => x.End != null);
TypeScript
.superRefine((v, ctx) => {  if (v.plan === "pro" && !v.company)    ctx.addIssue({ code: "custom", path: ["company"], message: "Company is required on the Pro plan" });  if (v.start && v.end && v.end < v.start)    ctx.addIssue({ code: "custom", path: ["end"], message: "End date must be on or after the start date" });})

Two copies, two languages, two teams. They agree on the day they’re written. Then someone changes one.

Rules as data

validonce is an open-source library that writes these rules once, on the server, as data. There are five kinds of rule. They cover most form validation that involves more than one field:

The server enforces them, publishes them in the OpenAPI document under x-validonce, and every client evaluates the same rules with the same semantics: what counts as blank, no type coercion, dates compared as dates. A shared conformance suite of 131 cases holds the C#, TypeScript, Python, Go and Java evaluators to identical results.

Today · two copies
Server · C#.When(x => x.Plan == "pro")
Frontend · copied by handif (v.plan === "pro" && …)
01 · Server rules
C# · FluentValidationRequiredWhen, Compare
Also FastAPI, Fastify, NestJS, Go and Spring Boot
02 · OpenAPI document
The rules travel as datacomponents.schemas.Signup"x-validonce": [ … ]
03 · Every frontend
validonce runtimeReactreact-hook-formAngularSignal / Reactive FormsVueVeeValidateWeb componentsvalidonce/domMobilenext release
The server always enforces every request
422 · broken rule, mapped back onto each field
412 · out-of-date rules, the form swaps in the current set

On the server: still FluentValidation

Install Validonce.AspNetCore and derive your validator from ValidonceValidator<T>, which is a FluentValidation AbstractValidator<T>. Validation that involves more than one field uses two new methods. Everything else stays plain FluentValidation.

C#
using Validonce;using Validonce.FluentValidation;public sealed class SignupValidator : ValidonceValidator<Signup>{    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");        RuleFor(x => x.Email).NotEmpty(); // ordinary FluentValidation still works    }}

Register it, and turn on the OpenAPI transformer:

C#
builder.Services.AddValidonce();builder.Services.AddOpenApi(o => o.AddValidonceSchemaTransformer());app.MapOpenApi();app.MapPost("/signups", (Signup s) => Results.Ok(new { ok = true })).WithValidonce();

A request that breaks a rule gets a 422 with the usual problem details, plus a machine-readable list of what failed. And /openapi/v1.json now carries the rules, using the JSON names your API serializes:

JSON
"Signup": {  "type": "object",  "properties": { "plan": { ... }, "company": { ... }, "start": { ... }, "end": { ... } },  "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" } },      { "id": "Signup.compare.end", "kind": "compare",        "left": { "field": "end" }, "op": "ge", "right": { "field": "start" }, "type": "date",        "message": { "key": "rules.end_after_start" } }    ]  }}

In the browser: read the rules, don’t rewrite them

The React form fetches the OpenAPI document (or extracts the rules at build time), and withRules attaches them to an ordinary Zod schema. react-hook-form doesn’t know anything changed.

TSX
import { zodResolver } from "@hookform/resolvers/zod";import { useForm } from "react-hook-form";import { rulesFromOpenApi } from "validonce/openapi";import { withRules } from "validonce/zod";import { z } from "zod";const doc = await (await fetch("/openapi/v1.json")).json();const rules = rulesFromOpenApi(doc, "Signup");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 schema = withRules(  z.object({    plan: z.enum(["free", "pro"]),    company: z.string().nullable(),    email: z.string().min(1, "Email is required"),    start: z.string().min(1, "Start date is required"),    end: z.string().nullable(),  }),  rules,  { messages },);const form = useForm({ resolver: zodResolver(schema) });

The messages are keys, so the browser can show its own wording and translations while the server stays language-neutral. Change the rule in C# and the form follows on the next load.

The server is still the authority: a client can be old, or skip the check. Its 422 maps back onto the same fields with the same messages:

TypeScript
import { fieldErrorsFromIssues, issuesFromResponse } from "validonce/server-errors";const res = await fetch("/signups", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values) });if (!res.ok) {  const body = await res.json().catch(() => null);  const errors = fieldErrorsFromIssues(issuesFromResponse(body), messages);  // { company: "Company is required on the Pro plan" }}

When the frontend is out of date

Sharing the rules fixes the copy problem and exposes a newer one: a frontend running old rules. A tab left open over lunch, rules bundled into last week’s build, a cached OpenAPI document, a mobile app nobody has updated. You change a rule on the server, and those forms keep checking yesterday’s version. The server still rejects bad input, but the user sees errors their form never showed them.

New in validonce 0.6, the server can tell. Each client sends a hash of the rules it checked with, in a Validonce-Rules header, and the server compares it with the rules it enforces. In report mode it handles the request and flags it, so you can count stale clients first. In enforce mode it answers 412 before your handler runs, with the current rules in the body:

The validonce playground with an ASP.NET Core backend and a React form. First, report mode: the server's rule changes so Canada needs a postal code, the open tab keeps the old rules, and on submit the user gets a postal code error from the server that the form never showed. Then enforce mode: the same change, and on submit the server answers 412, the form swaps in the new rules, keeps the user's answers and highlights the postal code field.
Report mode first, which is how production behaves today. Then enforce mode. Recorded on the playground.
C#
builder.Services.AddValidonce(o =>{    o.Rules = RulesMode.Enforce;      // Off (default), Report or Enforce    o.IncludeRulesWhenStale = true;   // send the current rules in the 412});

The browser swaps in the new rules and re-checks what the user already typed, so the new error shows up right in the form, with no reload and no lost input:

TypeScript
import { isStaleRules, liveRules, recoverStaleRules, rulesHeader } from "validonce";const live = liveRules(rules, { schema: "Signup" });   // rules the form can swapconst schema = withRules(baseSchema, live, { messages });const res = await fetch("/signups", {  method: "POST",  headers: { "Content-Type": "application/json", ...rulesHeader(live) },  body: JSON.stringify(values),});const body = await res.json().catch(() => null);if (isStaleRules(res.status, body)) {  await recoverStaleRules(live, body);   // take the current rules from the 412  await form.trigger();                  // re-check what the user typed; nothing is lost}

The keeping clients current guide covers the other five backends, a grace period for the last release’s rules, and a CI check that fails the build when bundled rules drift. The playground’s “Simulate a rule change” button shows it end to end.

One set of rules, every frontend

The same rule set runs in React, Angular, Vue and plain HTML forms, and every evaluator passes the same conformance suite. So the checkout form, the admin tool built in another framework and the embedded widget reject exactly the same inputs, with the same messages. The playground shows four frontends checking one set of rules.

Mobile is next: React Native, Android and iOS clients are planned for the next release, held to the same suite. A rule checked in your web app will give the same answer in your mobile app, down to the error message.

What it won’t do

Some checks shouldn’t move, and the format is deliberately small so it says no clearly. Arithmetic between fields (subtotal + tax == total), comparisons against “now”, and anything that calls a database or a service (“this email is already registered”) stay in your FluentValidation code, on the server. A rule can also be marked .ServerOnly() when the browser shouldn’t run it.

Try it

validonce is Apache-2.0, on NuGet as Validonce.AspNetCore and on npm as validonce. Issues and ideas are welcome on GitHub.