fluentvalidation
Validators with FluentValidation 12 in .NET code. Covers rules, cascade mode, error codes, child and collection validators, async rules, DI registration, the call from a minimal API endpoint filter, a controller, or a worker, the error response with stable codes, and validator tests. Use when code or a review touches AbstractValidator, RuleFor, RuleForEach, MustAsync, WithErrorCode, CascadeMode, SetValidator, IValidator, ValidateAsync, AddValidatorsFromAssemblyContaining, TestValidate, InlineValidator, FluentValidation.AspNetCore, or a move from DataAnnotations or AddValidation to FluentValidation. Not for the built-in AddValidation with DataAnnotations alone, ProblemDetails wiring, or endpoint design (dev-stack:aspnetcore), options validation at startup, or domain invariants inside entities (dev-stack:csharp).
- License 许可
- MIT
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- fluentvalidation
- metadata
- { "verified": "2026-10-27", "versions": "FluentValidation 12.2.0 and FluentValidation.DependencyInjectionExtensions 12.2.0 (net8.0 and later), .NET 10 (SDK 10.0.403)" }
- description
- Validators with FluentValidation 12 in .NET code. Covers rules, cascade mode, error codes, child and collection validators, async rules, DI registration, the call from a minimal API endpoint filter, a controller, or a worker, the error response with stable codes, and validator tests. Use when code or a review touches AbstractValidator, RuleFor, RuleForEach, MustAsync, WithErrorCode, CascadeMode, SetValidator, IValidator, ValidateAsync, AddValidatorsFromAssemblyContaining, TestValidate, InlineValidator, FluentValidation.AspNetCore, or a move from DataAnnotations or AddValidation to FluentValidation. Not for the built-in AddValidation with DataAnnotations alone, ProblemDetails wiring, or endpoint design (dev-stack:aspnetcore), options validation at startup, or domain invariants inside entities (dev-stack:csharp).
02 资源文件 12
- 参考文档references/call-sites.md6.9 KB
- 参考文档references/decisions.md2.9 KB
- 参考文档references/language.md4.7 KB
- 参考文档references/review-checklist.md3.5 KB
- 参考文档references/sources.md5.2 KB
- 参考文档references/stack-rules.md7.6 KB
- 参考文档references/testing.md4.0 KB
- 参考文档references/validators.md8.2 KB
- 参考文档rules.json7.6 KB
- 脚本scripts/convert.py2.9 KB
- 脚本scripts/doccheck.py28.8 KB
- 脚本scripts/stackcheck.py11.9 KB
03 SKILL.md 正文
FluentValidation
Validators and the call that runs them. The endpoint, ProblemDetails, and the built-in AddValidation are in dev-stack:aspnetcore. This skill also works in a worker or a library without a web host.
First
- Read
references/stack-rules.md. - Read the version gate:
- The
FluentValidation*packages in*.csprojorDirectory.Packages.props. - 12.x: use this file.
- 11.x: the rules apply, but the 12.0 removals still compile there. Tell the human about the upgrade. Do not upgrade unless the task asks for it. The upgrade steps are in
references/validators.md. FluentValidation.AspNetCorein the project: its owner deprecated it. Plan its removal (rule 1).
- The
- Find the other validation in the same request path. Look for
builder.Services.AddValidation(), DataAnnotations on the request records,[ApiController]model validation, and manual checks in the handler.
Done when you can name the FluentValidation version, the call site (filter, controller, worker), and each other validation that runs for the same request type.
Defaults for new code
Existing code keeps its style. For new code, use the accepted decision in docs/dev-team/decisions.md. When a decision has no accepted answer, ask the human (stack rule 4). The detail is in references/decisions.md.
| Area | Default | ID |
|---|---|---|
| Library | FluentValidation when the project uses it. Built-in AddValidation for shape rules only |
API-08 |
| Error codes to the client | code = "validation.failed" plus an errorCodes map per field, the same shape for both validation paths |
API-20 |
| Code format | WithErrorCode in the format of the ProblemDetails code (order.sku_unknown) |
API-04 |
| Call site | One generic endpoint filter for minimal APIs. An explicit ValidateAsync in controllers and workers |
API-08 |
| Auto-validation packages | None: no FluentValidation.AspNetCore, no SharpGrip |
API-08 |
| Lifetime | The library default (scoped) | - |
| Uniqueness and state | A unique index with 409, and the rule in the domain. A validator check is only an early message | - |
Rules
Packages and registration
- Reference
FluentValidationandFluentValidation.DependencyInjectionExtensionswith the same 12.x version. Do not addFluentValidation.AspNetCore: its owner deprecated it, and it works for MVC only. Its auto-validation cannot run async rules: a validator with an async rule throwsAsyncValidatorInvokedSynchronouslyExceptionat run time. - Register with
services.AddValidatorsFromAssemblyContaining<T>()andusing FluentValidation;. The namespaceFluentValidation.DependencyInjectionExtensionsdoes not exist, although a docs page shows it (CS0234). - Make validators
public, or passincludeInternalTypes: true. The scan skipsinternalvalidators, and the gap shows only at runtime as a DI error. - Keep the default lifetime (scoped). A singleton validator that takes a
DbContextor another scoped service holds one instance for all requests.
The call
- Call
await validator.ValidateAsync(model, ct)in async code.Validateon a validator with aMustAsyncrule throwsAsyncValidatorInvokedSynchronouslyException. A later async rule then turns each request into a 500. - Check the model for null before the call.
ValidateAsync(null)throwsInvalidOperationException. In Production, minimal APIs run the endpoint filters with a JSONnullbody, so a filter gets null (tested). In Development,ThrowOnBadRequestthrowsBadHttpRequestExceptionbefore the filters, so a test in Development does not show the problem. - Validate one request type with one library. With
AddValidation()in the project, remove the DataAnnotations from a type with a validator. Or call.DisableValidation()on the endpoint. The built-in filter runs first and returns its own 400 (tested). The validator then never runs for that field, and the client sees two error styles. - Return
TypedResults.ValidationProblem(result.ToDictionary(), extensions: ...)with the codes in an extension (decision API-20).ToDictionary()carries the messages only. The defaultErrorCodeis the validator name (NotEmptyValidator), which is not a contract.
Filter, controller, worker, and the error shape: references/call-sites.md.
Rules in a validator
- Set
WithErrorCodeafter each validator that a client acts on. It applies to the last validator before it, not to the whole chain. Use the format of API-04 (order.lines_too_many). - Set
RuleLevelCascadeMode = CascadeMode.Stopin the constructor when a later check needs an earlier one (NotEmpty, thenMatches, thenMustAsync). It stops a second message and a null access inMust. - Do not set
ClassLevelCascadeMode = CascadeMode.Stop. It stops the whole validator after the first rule that fails, not each field. The client then gets one field error at a time (tested). - Compose with
RuleForEach(x => x.Lines).SetValidator(lineValidator)and the child validator from the constructor. FluentValidation 12.0 removedInjectValidator(CS1061). SetValidatorskips a null item or child. When the value is required, put.NotNull().WithErrorCode(...)beforeSetValidator, else the handler throws. Null can also be a valid value, for example an optional field on an update that keeps the current value. ThenSetValidatorwithoutNotNull()is correct. Do not flag it. WithCascadeMode.Stop, aRuleForEachstops at the first bad item and does not check the other items. Add.Cascade(CascadeMode.Continue)to that rule when the client needs an error for each item (tested).- Validate the shape of the input: required, length, range, format, and cross-field rules inside one request. Keep state rules in the domain, for example "only a placed order can ship". Keep uniqueness in a unique index with a 409. A validator runs only on the paths that call it. Two requests can pass the same check at the same time.
- Read limits from the options class that holds them (
IOptions<T>in the validator constructor). Do not copy a number into a second place. When a request names a limit that differs from the option, ask which one wins. - Write two validators for two contracts. Do not use rule sets for it: they hide which rules run, and they pass into child validators.
Rule examples and the 12.0 removals: references/validators.md.
Tests
- Test the real validator with
TestValidateAsync(valid and invalid case per rule, and the code). UseInlineValidator<T>when a consumer test needs a validator that fails. Do not mockIValidator<T>: the mock hides a missing registration and a sync call.
Test examples: references/testing.md.
Never write
| Wrong | Correct |
|---|---|
AddFluentValidationAutoValidation(), AddMvc().AddFluentValidation(...) |
AddValidatorsFromAssemblyContaining<T>() and an endpoint filter |
using FluentValidation.DependencyInjectionExtensions; |
using FluentValidation; |
internal sealed class CreateOrderValidator with a default scan |
public sealed class, or includeInternalTypes: true |
AddValidatorsFromAssemblyContaining<T>(ServiceLifetime.Singleton) with a scoped dependency |
AddValidatorsFromAssemblyContaining<T>() |
var result = validator.Validate(request); in an endpoint or filter |
var result = await validator.ValidateAsync(request, ct); |
context.GetArgument<T>(0) passed to the validator as is |
context.Arguments.OfType<T>().FirstOrDefault() is not { } argument and a 400 |
CascadeMode = CascadeMode.StopOnFirstFailure; |
RuleLevelCascadeMode = CascadeMode.Stop; |
ClassLevelCascadeMode = CascadeMode.Stop; to get one message for each field |
RuleLevelCascadeMode = CascadeMode.Stop; (rule 11) |
RuleForEach(x => x.Lines).SetValidator(lineValidator) when an item can be null |
RuleForEach(x => x.Lines).NotNull().WithErrorCode("order.line_required").SetValidator(lineValidator) |
RuleFor(x => x.Address).InjectValidator(); |
Inject IValidator<Address> and call SetValidator(addressValidator) |
Transform(x => x.Name, n => n.Trim()) |
Project the value in the rule expression or in the request mapping |
.NotEmpty().MaximumLength(32).WithErrorCode("sku_invalid") for both checks |
.NotEmpty().WithErrorCode("order.sku_required").MaximumLength(32).WithErrorCode("order.sku_too_long") |
TypedResults.ValidationProblem(result.ToDictionary()) when the client reads codes |
The same plus the code and errorCodes extensions (API-20) |
result.Errors.GroupBy(e => e.PropertyName).ToDictionary(..., e.ErrorMessage ...) |
result.ToDictionary() |
[Required] on the record and a validator for the same field |
One of the two (rule 7) |
new Mock<IValidator<CreateOrder>>(), Substitute.For<IValidator<...>>() |
new CreateOrderValidator(...) or new InlineValidator<CreateOrder>() |
ShouldHaveAnyValidationError() |
ShouldHaveValidationErrors() (12.x) |
MustAsync(EmailNotTakenAsync) as the only guard |
A unique index, catch the violation, return 409 |
Check
-
Build with the analyzers. Pass: 0 warnings and 0 errors. The 12.0 removals fail here (CS0117, CS0118, CS0103, CS1061).
dotnet build -warnaserror -
Find deprecated packages. Pass: no
FluentValidation.AspNetCore.dotnet list package --deprecated -
Run the rule check of this skill. Pass:
stackcheck: 0 errors. In an existing project, add--changed <base branch>.python3 <skill folder>/scripts/stackcheck.py --root <repo> -
Run the tests. Pass: all green. Each rule has a
TestValidateAsynctest (valid and invalid, with the code). Each endpoint has one HTTP test that asserts the 400 and its codes.dotnet test
Review checklist
The full list is in references/review-checklist.md.
- No
FluentValidation.AspNetCore, noAddFluentValidation*. tool (FV-PKG-ASPNETCORE, FV-AUTOVALIDATION) - Each call is
ValidateAsyncwith the token. tool (FV-SYNC-VALIDATE) - A filter checks the argument for null before the call. judge
- Validators are
public, or the scan hasincludeInternalTypes: true. judge - The lifetime is the default, or no validator takes a scoped service. tool (FV-SINGLETON) and judge
- One library per request type: no DataAnnotations and no
AddValidationfilter next to a validator. judge - Each rule that a client acts on has its own
WithErrorCode. The codes reach the response (API-20). tool (FV-MANUAL-DICTIONARY) and judge RuleLevelCascadeMode = CascadeMode.Stopwhere a check needs an earlier one. NoClassLevelCascadeMode = CascadeMode.Stop. tool (FV-CASCADE-DEPENDENT, FV-CLASS-CASCADE-STOP)- Child validators come in through the constructor and
SetValidator. ARuleForEachwith items that can be null hasNotNull(). tool (CS1061 forInjectValidator) and judge - No state rule or uniqueness check as the only guard in a validator. judge
- Limits come from the options class, not from a second literal. judge
- Tests use the real validator or
InlineValidator<T>, not a mock. tool (FV-MOCK-VALIDATOR) - The endpoint documents its 400 (
ProducesValidationProblem,dev-stack:aspnetcore-openapi). judge
Existing code
Stack rule 3 applies. For this skill, check these defects in the existing code that the change touches:
- A sync
Validatecall on a validator that gets aMustAsyncrule, also in an import or a worker without an HTTP test (rule 5). - A filter without a null check, or that returns
ToDictionary()without the codes (rules 6 and 8). - DataAnnotations on a type that gets a validator while
AddValidation()is on (rule 7). - One
WithErrorCodeafter a chain of validators (rule 9), and a limit that the handler checks a second time (rule 15).
Report
End with the report of stack rule 8 (references/stack-rules.md). Output text follows references/language.md.
After a change to an endpoint, add a table of the error codes below the "Changes" table. Give each code that a client can get from the endpoint, with its field (the property path, for example Lines[0].Sku) and the HTTP status. Also give where the code is in the response (the errorCodes extension, decision API-20). Include the existing codes that the endpoint keeps. The client team builds on this list.
References
references/validators.md: read when you write a validator, a child or collection rule, an async rule, or upgrade from 11.x.references/call-sites.md: read when you call a validator from an endpoint filter, a controller, or a worker, or shape the error response.references/testing.md: read before you write a validator test or an endpoint test that involves validation.references/decisions.md: read when new code needs decision API-08 or API-20.references/review-checklist.md: read when you review a change.references/sources.md: the primary sources and the date of each check.references/stack-rules.md: the common rules of each dev-stack skill.references/language.md: the rules for text output.scripts/stackcheck.py: the rule check of this skill.
04 同仓库更多 Skills
web-accessibility
Web accessibility to WCAG 2.2 AA - a checklist for the design, the tool checks (axe-core, the Tab walk, reduced motion), and the manual checks that no tool does (screen reader, zoom, status messages) - with the EAA and EN 301 549 status. Use when a design, mockup, or built feature must be checked for accessibility, when a review must cover keyboard and screen reader use, when the user asks about focus, a focus trap, contrast, or a screen reader on a page, or when the user asks which accessibility rules apply.
ux-states
State inventory for each screen - default, empty, loading, partial, error, success, disabled, overflow, offline, and the business states (no permission, stale data, locked by another user, waiting on an external system, bulk result with failures, read only) - with what the user sees, can do, and how the user recovers. Use when a screen or flow needs its states designed or checked, or when a design shows only the happy path.
ux-setup
Set up a project for UX work - finds the design tools, the design-system source, the brand files, the languages, and the run command, asks the human one round of questions, and writes the "## Design" section of .claude/rules/delivery.md that the ux-design commands and the ux-designer agent read. Moves an older "## Design" section out of CLAUDE.md. Use when /setup, /ux-design, or /ux-review needs the design facts, when the ux-designer agent returns NEEDS_HUMAN because the "## Design" section is missing, or when the user wants to set up or change the design tools of a project.
ux-review
UX review of a built feature against its approved design - Playwright walks each flow and state at 390, 820, and 1440 px, axe-core and the tell checks run on each state, and each heuristic gets a verdict - with findings by owner, severity, and origin, and a verdict in ux-review.md in the work folder of the item. Use when a built feature or screen must be checked against its design, mockups, or prototype, in each state or at each screen size, when built screens need findings by severity, when the build of an item with a UX design is done, or when existing screens need a UX audit.
ux-prototype
Clickable prototype of a designed story in the proto-shell standard, with variants for an A/B test, all states in scope, three sizes, and a test plan with tasks. Use when a design or mockups exist and the team must test the flow or compare variants with users before the build.
ux-practice
The method of the ux-designer agent for the UX design of a story, a feature, or a screen - Double Diamond phases, a design spec with a source for each decision, the UX decision log, evidence tags, severity, and the modes light, full, and new-direction. Preloaded by the ux-designer agent. Use when the ux-designer agent or another UX skill names this method. For the design of an item, a person starts ux-design:ux-design.