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:
- Company is required when the user has selected the Pro plan.
- The end date can’t be before the start date.
- The user must give an email or a phone number.
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:
RuleFor(x => x.Company).NotEmpty().When(x => x.Plan == "pro");RuleFor(x => x.End).GreaterThanOrEqualTo(x => x.Start).When(x => x.End != null);.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:
- required_when: a field is required when a condition holds (
planis"pro"). - compare: one field against another or a constant (
end >= start, dates, numbers or strings). - at_least_one_of: email or phone.
- exactly_one_of: card or invoice, not both.
- all_or_none: street, city and zip together.
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.
.When(x => x.Plan == "pro")if (v.plan === "pro" && …)RequiredWhen, Comparecomponents.schemas.Signup"x-validonce": [ … ]react-hook-formAngularSignal / Reactive FormsVueVeeValidateWeb componentsvalidonce/domMobilenext releaseOn 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.
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:
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:
"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.
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:
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:

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:
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
- The playground runs a live ASP.NET Core backend with a React form; swap in Angular, Vue or a plain HTML form, or a different backend, without changing the rules.
- Getting started with ASP.NET Core and the React guide on the docs site.
- Already have a pile of
Whenclauses? The validonce Claude Code plugin finds them in the validators you already have and drafts the rules, and its full version proves nothing changed by running your old validator against the new rules on generated inputs. See migrating with an agent. - If you find this useful, please give validonce a star on GitHub. It helps other developers find it.
validonce is Apache-2.0, on NuGet as Validonce.AspNetCore and on npm as validonce. Issues and ideas are welcome on GitHub.