Onboarding guide
6. Validation
What this group covers. This is the framework-level validation kit that
MMCA.Common.Application ships so every module validates input the same way. It has four parts:
(1) a set of composable FluentValidation rule sets, ten general-purpose ones in
CommonValidationRules.cs (RequiredStringRules<T>,
OptionalStringRules<T>, EmailRules<T>,
AbsoluteUrlRules<T>, PositiveIntRules<T>,
PositiveDecimalRules<T>, NonNegativeIntRules<T>,
RequiredIdRules<T, TId>,
OptionalPositiveIdRules<T, TId>,
StrongPasswordRules<T>) plus the
six address-field rules (AddressLine1Rules<T>,
AddressLine2Rules<T>, CityRules<T>,
StateRules<T>, ZipCodeRules<T>,
CountryRules<T>) and the AddressValidator that assembles
them, plus two opt-in United States rules (UsStateRules<T>,
UsZipCodeRules<T>) that an app composes on
top under its own country condition; (2) the shared helper that gives every one of those rules an
optional machine-readable code, or one code per rule,
OptionalErrorCodeExtensions; (3) one convention validator,
CommandRequestValidator<TCommand, TRequest>, that
bridges a command to its request's validators; and (4) one failure-mapping extension,
ValidationFailureExtensions, that turns FluentValidation output
into domain Error values with a stable wire code. Riding
along in the same namespace family is CurrentUserServiceExtensions,
the caller guard that answers the other pre-execution question a handler asks ("is there an
authenticated user at all?"). The per-feature validators that consume all of this (ADC's
SessionEventIdRules<T>, Store's ProductCategoryIdRules<T> and CheckoutAddressRequestValidator)
live in their module chapters, and the framework's own auth request validators
(RegisterRequestValidator and its change-password and reset-password peers, under
MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/) are composed from these rule sets
too. The external library underneath is FluentValidation 12
(primer §3); nothing here hand-rolls
validation.
Where validation sits in the request lifecycle. Validation is not invoked by handlers. It is a
cross-cutting stage of the CQRS pipeline
(primer §2), governed by
ADR-014. The shipped command
chain runs FeatureGate -> Authorization -> Logging -> Caching -> Validating -> Timeout ->
Transactional -> handler, and the query chain is the same minus the transaction. Two decorators feed
on this chapter's types: ValidatingCommandDecorator<TCommand, TResult>
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidatingCommandDecorator.cs:31)
and ValidatingQueryDecorator<TQuery, TResult>
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidatingQueryDecorator.cs:34),
the second added by the ADR's 2026-08-26 revision so that a query carrying paging or filter input is
gated the same way a command is. Placement is the point: the Validating stage sits before
TransactionalCommandDecorator<TCommand, TResult>,
so an invalid command short-circuits before a database transaction is ever opened
(ValidatingCommandDecorator.cs:23-26). [Rubric §6, CQRS & Event-Driven] assesses whether reads
and writes are separated and whether cross-cutting behavior lives in the pipeline rather than inside
use cases: validation here is one decorator, not an if (!valid) return prologue copied into every
handler. [Rubric §12, Performance & Scalability] and [Rubric §24, Forms, Validation & UX Safety]
apply for the same reason: one gate, uniform for REST, gRPC, and event-consumer entry points alike.
Every registered validator runs, and they run sequentially. Both decorators materialize their
injected IEnumerable<IValidator<T>> into an array once
(ValidatingCommandDecorator.cs:36, ValidatingQueryDecorator.cs:39) and, when that array is empty,
call the inner handler untouched (ValidatingCommandDecorator.cs:41, ValidatingQueryDecorator.cs:44),
so a use case with no validator costs nothing. When validators exist, both decorators hand the array
to the shared internal ValidationGate.ValidateAsync (ValidatingCommandDecorator.cs:46,
ValidatingQueryDecorator.cs:49), which loops over all of them and unions their failures
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidationGate.cs:30-46)
rather than honoring only the first registration. That semantic
is deliberate and is recorded as the 2026-08-31 correction on ADR-014: a use case commonly carries a
module-authored validator beside a framework-supplied one, and stopping at the first registration
would turn the others into silently unenforced dead code
(ValidatingCommandDecorator.cs:17-21). The loop is sequential on purpose, not a Task.WhenAll: a
validator is free to reach the database through a scoped repository and a DbContext is not
thread-safe (ValidationGate.cs:27-29). The gate returns null when every validator passes
(ValidationGate.cs:21, :46); only when at least one failure is collected does the decorator build
a typed failure and return it without calling the handler (ValidatingCommandDecorator.cs:47-53).
The failure-mapping boundary. FluentValidation speaks ValidationResult and ValidationFailure;
the rest of the codebase speaks the Result pattern
(ADR-013).
ValidationFailureExtensions
(MMCA.Common/Source/Core/MMCA.Common.Application/Extensions/ValidationFailureExtensions.cs:10) is
the bridge: a C# extension(ValidationResult) block
(primer §4) whose public ToErrors(source)
(ValidationFailureExtensions.cs:62-63) delegates to the internal ToGateErrors, which projects each
failure into Error.Validation(WireCode(f), f.ErrorMessage, source, f.PropertyName)
(ValidationFailureExtensions.cs:80-88). The wire code keeps a code the rule set supplied, but rewrites
a FluentValidation default code (the validator class name, such as NotEmptyValidator) into
{PropertyPath}.{Rule} (Email.Required), and gives a failure that carries no code at all
{PropertyPath}.Invalid, so neither an implementation class name nor an empty code reaches the wire
(SynthesizeWireCode at ValidationFailureExtensions.cs:94-121, the rule-word table at :28-43).
The gate calls ToGateErrors directly with a flag saying whether the validated type wraps a request
through ICommandWithRequest<out TRequest>;
for such a command the leading Request. segment is dropped from a synthesized code only, so a
default-coded rule answers under the same code whether its validator ran over the bare request or over
the command that embeds it, while the error's target keeps the full path
(ValidationFailureExtensions.cs:112-118, the flag computed once per type at ValidationGate.cs:57-62).
Error.Validation stamps
ErrorType.Validation
(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:46-47). The shared gate passes the
use-case type name as the source (ValidationGate.cs:42), so a downstream consumer can see which command or query produced
the failures, and the failing property name travels as the error's target. ErrorType.Validation
is what the edge maps to HTTP 400: the client-side reader carries the inverse mapping explicitly
(MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:108), and the
severity table ranks Validation at the caller-can-fix-it end so a multi-error failure is never
downgraded from a 403 or 500 to a 400
(MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorTypeSeverity.cs:50). Nothing in the
domain references FluentValidation, and FluentValidation never sees an Error: neither library knows
the other exists, which is [Rubric §3, Clean Architecture] (dependencies point inward, the external
library stays at the Application boundary) and [Rubric §9, API and Contract Design] (one uniform
failure contract for every endpoint).
The rule sets: composition over copy-paste. Each rule class in
MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs is a tiny
AbstractValidator<T> generic over the parent type, taking an Expression<Func<T, ...>> selector
in its constructor and declaring its rules in an expression-bodied constructor. Because they are
generic-plus-selector, the same EmailRules<T>
(CommonValidationRules.cs:112) validates a value object, a request DTO, or a command; a module
composes it with FluentValidation's Include(...) instead of rewriting "non-empty, valid format, max
length" each time. The bounds are parameters, never literals in the rule: the framework's own
registration validator passes its EmailMaxLength constant into EmailRules<RegisterRequest> and pairs it with
StrongPasswordRules<T> and two
RequiredStringRules<T>
(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:31-34,
the constant at :23).
StrongPasswordRules<T>
takes its bounds from PasswordComplexity rather than from the caller: MinimumLength (8) and
MaximumLength (128) (CommonValidationRules.cs:255-256, the constants at
MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:21, :24), plus four
complexity Matches rules for uppercase, lowercase, digit, and special character
(CommonValidationRules.cs:257-260). With a codePrefix each rule answers under its own code
(.Required, .MinLength, .MaxLength, .Uppercase, and so on; CommonValidationRules.cs:243-245).
That rule is [Rubric §11, Security] territory: the complexity policy is defined once, in
PasswordComplexity, which the client form attribute also evaluates, so the server rule and the
form cannot disagree (CommonValidationRules.cs:241-242).
[Rubric §1, SOLID] (one rule set, one responsibility; the composite assembles rather than
duplicates) and [Rubric §15, Best Practices and Code Quality] (no copy-pasted limits or messages)
are what the whole file is optimizing for.
One field, one error code. Every rule class takes an optional trailing errorCode, and
OptionalErrorCodeExtensions.WithOptionalErrorCode
(CommonValidationRules.cs:22, the method at :65-67) is the internal helper that applies it:
it returns the rule unchanged when the code is null, so every existing call site that omits it
behaves exactly as before, and calls FluentValidation's WithErrorCode when one is supplied. The
code is applied to every rule the class declares for that field, so one field answers under one
code (CommonValidationRules.cs:14-17). A rule class that declares more than one rule also takes an
optional codePrefix instead, and each rule then answers under {codePrefix}.{Rule}
(Register.Password.MinLength), so a field whose separate bounds must answer under distinct codes
composes the same rule class rather than re-declaring its rules (CommonValidationRules.cs:17-20,
WithRuleCode at :35-37); a class given both an errorCode and a codePrefix throws an
ArgumentException (EnsureOneCodeShape at :46-54). This is what lets modules subclass a framework rule instead of
bypassing it: ADC's SessionEventIdRules<T> derives from
RequiredIdRules<T, TId> and passes "Session.EventId.Required"
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/Validation/SessionValidationRules.cs:24-29),
and Store's ProductCategoryIdRules<T> derives from
OptionalPositiveIdRules<T, TId> with
"Product.CategoryId.Invalid"
(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Products/Validation/ProductValidationRules.cs:47-51).
The two id rules also encode a deliberate difference in what "missing" means:
RequiredIdRules<T, TId> uses NotEmpty, which rejects both 0 for an
integer key and Guid.Empty for a GUID key (CommonValidationRules.cs:211-216, the
remarks at :203-205), while OptionalPositiveIdRules<T, TId> uses
GreaterThan(default(TId)) on a nullable and relies on FluentValidation skipping a comparison rule
when the property is null, so "positive when provided" needs no When clause and no per-pass
recompiled selector (CommonValidationRules.cs:230-235, the remarks at :224-226).
One rule that shares its check with the domain. AbsoluteUrlRules<T>
(CommonValidationRules.cs:151) is the exception to "rule sets are self-contained": besides the
length bound it calls Must(BeAnAbsoluteHttpUrl) (CommonValidationRules.cs:158), and that predicate
delegates to CommonInvariants.EnsureUrlIsWellFormed
(CommonValidationRules.cs:161-162, the invariant at
MMCA.Common/Source/Core/MMCA.Common.Domain/Invariants/CommonInvariants.cs:293-297) and keeps only
its IsSuccess. The validator and the domain invariant therefore answer identically, by construction
rather than by convention. What it buys is concrete: a plain bounded-string treatment accepts
javascript: and data: values that become executable the moment a link or an image renders them,
and the invariant's own suppression note says the check must run on the untrusted string, before
anything constructs a Uri from it (CommonInvariants.cs:289-292). Null or empty passes, since the
fields are optional (CommonInvariants.cs:295). ADC applies it to every stored external link:
sponsor logo, website, and LinkedIn URLs
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sponsors/Validation/SponsorValidationRules.cs:35,
:64, :82), speaker LinkedIn and GitHub URLs
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/Validation/SpeakerValidationRules.cs:80,
:84), and the event sponsorship-packet and ticketing URLs
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/Validation/EventValidationRules.cs:143,
:105). [Rubric §11, Security] assesses whether untrusted input is constrained at the boundary
before it reaches a rendering surface; this rule is where that happens for URLs.
The address family, a worked example of composition. The six rules in
MMCA.Common/Source/Core/MMCA.Common.Application/Validation/AddressValidationRules.cs follow the
same generic-plus-selector shape, and their length bounds come from
AddressInvariants constants rather than
literals (AddressValidationRules.cs:37, :47, :57, :67, :77, :87), so the value object and
its validator cannot disagree. Only line 1 is required (NotEmpty at AddressValidationRules.cs:36);
the other five are max-length only. AddressValidator
(AddressValidationRules.cs:13) then Includes all six against the
Address value object
(AddressValidationRules.cs:17-22). Consumers pick whichever half they need: the framework's own
registration validator and Store's customer create and change-address validators attach the whole
composite with SetValidator(new AddressValidator())
(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:36-38,
MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Customers/UseCases/Create/CustomerCreateRequestValidator.cs:20,
MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Customers/UseCases/ChangeAddress/CustomerChangeAddressRequestValidator.cs:18),
while a DTO that flattens address fields without an Address wrapper can include the individual
rule sets instead (AddressValidationRules.cs:9-11).
The US address variant: stricter rules layered on, never swapped in.
The two US rule classes in
MMCA.Common/Source/Core/MMCA.Common.Application/Validation/UsAddressValidationRules.cs are composed
by an app that takes United States addresses, on top of the length rules every address gets from the
plain AddressValidator and under whatever country condition the app applies
(UsAddressValidationRules.cs:12-14). There is no US city rule: a required city is a plain
RequiredStringRules<T>,
which also bounds the length (UsAddressValidationRules.cs:14-15). UsStateRules<T>
(UsAddressValidationRules.cs:18) requires the state and then checks it with
Must(UsPostalRegions.IsKnownCode) (UsAddressValidationRules.cs:25), and
UsZipCodeRules<T> (UsAddressValidationRules.cs:33) requires the ZIP code and
then checks Must(UsPostalRegions.IsValidZipCode) (UsAddressValidationRules.cs:40). With a
codePrefix they answer under .Required plus .Unknown for the state and .Invalid for the ZIP
code (UsAddressValidationRules.cs:24-25, :39-40). Both run
under Cascade(CascadeMode.Stop) (UsAddressValidationRules.cs:23, :38), so an empty value reports only "You must enter a ..." and never a
second format message. The two predicates live on
UsPostalRegions in MMCA.Common.Shared
(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/UsPostalRegions.cs:12), deliberately,
so a UI's state picker and the server validator accept exactly the same codes
(UsPostalRegions.cs:6-11): the 50 states, DC, five territories and three military regions, matched
case-insensitively with surrounding spaces ignored (UsPostalRegions.cs:34-35, :43), and a ZIP of
5 digits or ZIP+4 through a generated, culture-invariant regex with a 100 ms match timeout
(UsPostalRegions.cs:66-71). The rules do not check the country: the caller decides which addresses
are US ones, and the plain AddressValidator is left unchanged
(UsAddressValidationRules.cs:12-14). Store's CheckoutAddressRequestValidator is the one consumer
today: it Includes UsStateRules<T> and UsZipCodeRules<T> inside a When on a United States
country
(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/Checkout/CheckoutDeliveryRequestValidator.cs:77-84);
ADC and Helpdesk compose neither.
Convention over configuration: the request-to-command bridge. Most commands wrap a request record
and implement ICommandWithRequest<out TRequest>
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommandWithRequest.cs:14). Rather than
make module authors write a validator for both the request and the command,
CommandRequestValidator<TCommand, TRequest>
(MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommandRequestValidator.cs:30) takes
the whole IEnumerable<IValidator<TRequest>> from the container, de-duplicates it by runtime type so
an assembly scanned twice does not report each failure twice, and attaches each one with
RuleFor(c => c.Request).SetValidator(validator) (CommandRequestValidator.cs:33-41). The wiring is
reflective and lives in the module scan: ScanModuleApplicationServices
(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:47) first calls
FluentValidation's AddValidatorsFromAssembly to pick up every hand-written validator by convention
(DependencyInjection.ModuleScanning.cs:81), then walks the assembly for types implementing
ICommandWithRequest<>, constructs the closed CommandRequestValidator<TCommand, TRequest>, and
registers it as IValidator<TCommand> with TryAddTransient, so an explicitly authored command
validator always wins (DependencyInjection.ModuleScanning.cs:83-98). Common's own validators are registered
separately in AddApplication via AddValidatorsFromAssemblyContaining<ClassReference>(), because
the per-module scan only sees the module's own assembly (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:67-70); that call
is what puts AddressValidator in the container. For a command the reflective
scan cannot see, for example a closed generic constructed at registration time,
AddCommandRequestValidator<TCommand, TRequest>() (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:220-226) is the explicit
form of the same registration, with the same TryAdd precedence. [Rubric §2, Design Patterns]
(convention over configuration, plus the Decorator pattern the gate itself rides on) and
[Rubric §15, Best Practices & Code Quality] (a new command inherits validation without a registration line) both
land here.
The caller guard that travels with this group.
CurrentUserServiceExtensions
(MMCA.Common/Source/Core/MMCA.Common.Application/Extensions/CurrentUserServiceExtensions.cs:9) is
not FluentValidation, but it answers the other question asked before a handler does work: it collapses
the read-then-null-check-then-fail block into
RequireUserId(code, message, errorType, source) on
ICurrentUserService, returning
Result<UserIdentifierType> and defaulting to ErrorType.Forbidden with the shared
"Access denied." message (CurrentUserServiceExtensions.cs:12, :35-46). The error code stays a
parameter because it names the module, which the framework cannot know. ADC's Engagement handlers use
it as their first statement ("CheckIns.Forbidden" in the five check-in handlers, for example
MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/CheckIns/UseCases/CheckInAttendee/CheckInAttendeeHandler.cs:35,
and "Points.Forbidden" in the two points handlers, for example
MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Points/UseCases/GetMyPoints/GetMyPointsHandler.cs:41).
Adopting it moved those codes out of the modules and into framework arguments, which is visible in
governance: ADC's error-catalog fitness test records lowering its scanned-code floor from 66 to 57
when those codes stopped being module literals the scanner could see
(MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Contracts/ErrorCatalogTests.cs:107-115),
and raising it again as later MMCA.Common scans learned to read framework code arguments back, to
the current floor of 238
(MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Contracts/ErrorCatalogTests.cs:118-131, :134). That is
[Rubric §34, Architecture Governance and Documentation] at work: a shared abstraction is not
adopted until the tests that measure the codebase are updated to match.
End to end, concretely. A request arrives at a controller or endpoint, is mapped to a command, and
is dispatched. The pipeline reaches the Validating stage, which resolves every IValidator<TCommand>
the container holds: hand-written ones found by the assembly scan, plus the auto-registered
CommandRequestValidator that forwards to the request's validators. Those validators run the composed
rule sets: ADC's session rules, for instance, derive SessionTitleRules<T> from
RequiredStringRules<T> and SessionEventIdRules<T> from
RequiredIdRules<T, TId>
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/Validation/SessionValidationRules.cs:13-14,
:24-25). If every validator passes, the Timeout and Transactional
decorators run and the handler executes inside a transaction. If any fails, the gate's
ToGateErrors call converts the union of failures into ErrorType.Validation errors, the decorator logs a debug line naming the
command and the error count (ValidatingCommandDecorator.cs:56-65) and returns a failed Result
without touching the database; the edge maps it to a 400 with per-property messages. All of it
lives in MMCA.Common.Application so ADC, Store, and Helpdesk inherit the same email, password,
address, id, and URL rules and the same auto-validation convention. Module validators express only
domain-specific rules on top. There is no ADR dedicated to validation: it is governed by
ADR-014 for the gate and its
placement, ADR-013 for the failure
contract the gate emits, and by the architecture fitness tests that keep the layering honest.
OptionalErrorCodeExtensions
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:22· Level 0 · class (internal static)
What it is: a three-member internal helper that lets every reusable rule fragment in
CommonValidationRules.csandUsAddressValidationRules.csaccept an optional machine-readable error code without any of them branching on it. It supports two code shapes: oneerrorCodefor every rule of a field, or acodePrefixthat gives each rule its own{codePrefix}.{Rule}code. Given neither, it hands the rule straight back untouched.Depends on: FluentValidation's
IRuleBuilderOptions<T, TProperty>(NuGet, imported atCommonValidationRules.cs:3). No first-party dependencies: this is the lowest primitive in the validation kit. Every rule class in the same assembly's two rule files calls it, and its output feedsValidationFailureExtensions, which copies the failure'sErrorCodeonto the domainError.Concept introduced, the machine-readable error code alongside the human message. A FluentValidation failure carries two independent strings: a
ErrorMessagemeant for a person and anErrorCodemeant for a program. Left alone, FluentValidation fills the code with the validator's name ("NotEmptyValidator","MaximumLengthValidator"), which is useless to a caller that wants to branch on "the question text was missing" rather than "some non-empty rule failed somewhere". The class remarks (CommonValidationRules.cs:13-21) record the failure mode this helper exists to close: module validators used to skip the shared bases entirely and hand-write the rule chain for the single reason that the bases set a message but no code, so a validator needing a stable code had nothing to compose with.[Rubric §9, API & Contract Design]assesses whether the contract a client codes against is stable and uniform; a caller-supplied code such as"Sponsor.EventId.Required"is part of that contract, where the FluentValidation default is an implementation detail that would change if the rule were re-expressed.[Rubric §15, Best Practices & Code Quality]: because the code rides in as one optional constructor argument, adding a coded rule never forks the shared fragment into a bespoke copy. The remarks (CommonValidationRules.cs:14-20) spell out the two shapes: anerrorCodeis applied to every rule the fragment declares for that field, so one field answers under one code, while a fragment that declares more than one rule also accepts acodePrefixunder which each rule answers separately (Register.Password.MinLength), so a field whose bounds must answer under distinct codes composes the same fragment rather than re-declaring its rules.Walkthrough: the class is
internal static(:22), so it is invisible outsideMMCA.Common.Application; consumers reach the behavior only through theerrorCodeandcodePrefixparameters on the rule classes. It has three members:WithRuleCode<T, TProperty>(rule, errorCode, codePrefix, ruleName)(:35-37) is the one the multi-rule fragments call per rule. With no prefix it falls back toWithOptionalErrorCode; with one it stampsWithErrorCode($"{codePrefix}.{ruleName}"), soRequiredStringRules<T>given"Register.FirstName"answers underRegister.FirstName.RequiredandRegister.FirstName.MaxLength.EnsureOneCodeShape(errorCode, codePrefix)(:46-54) throws anArgumentExceptionnamingcodePrefixwhen a caller supplies both, because the two describe different code shapes and accepting both would silently drop one (:40-41). Every fragment that takes a prefix and anerrorCodecalls it first.WithOptionalErrorCode<T, TProperty>(rule, errorCode)(:65-67) is an expression body that readserrorCode is null ? rule : rule.WithErrorCode(errorCode). Returning the sameIRuleBuilderOptionsin the null case is what makes it chainable in the middle of a fluent rule chain, and is what preserves the behavior of the many callers that omit the code (:57-58documents exactly that intent).
Why it's built this way: the alternative (an
ifinside each rule constructor) would have repeated the null check and the prefix formatting in every fragment. Making the resolution an extension keeps every rule chain a single fluent expression while giving both files a uniform code behavior, and the guard makes the invalid combination fail at construction rather than at the first failed validation.Where it's used: only inside
MMCA.Common.Application.WithOptionalErrorCodedirectly in the single-code fragments (CommonValidationRules.cs:96,:173,:184,:195,:216,:235);WithRuleCodein the prefix-capable ones (:83-84,:125,:127,:157-158,:254-260) and in the two US address fragments, which passnullfor the single code (UsAddressValidationRules.cs:24-25,:39-40);EnsureOneCodeShapeat the top of the four constructors that take both parameters (CommonValidationRules.cs:81,:123,:155,:252).
RequiredStringRules<T>, OptionalStringRules<T>, EmailRules<T>, PositiveIntRules<T>, PositiveDecimalRules<T>, NonNegativeIntRules<T>, RequiredIdRules<T, TId>, OptionalPositiveIdRules<T, TId>, PasswordRules<T>, StrongPasswordRules<T>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs· Levels 0 to 4 · classes (AbstractValidator<T>subclasses)
What it is: nine reusable FluentValidation rule fragments, each enforcing exactly one field contract (a required string with a length ceiling, a positive integer, a supplied identifier, a strong password). A request or command validator composes them with FluentValidation's
Include()instead of restating the sameRuleForchain. Each member, with its source line and the rule chain its constructor builds:Type File:Line Rule chain (each rule coded through OptionalErrorCodeExtensions)RequiredStringRules<T>CommonValidationRules.cs:77NotEmpty()+MaximumLength(maxLength);errorCodeorcodePrefixOptionalStringRules<T>CommonValidationRules.cs:92MaximumLength(maxLength)only (nullable selector, null passes)EmailRules<T>CommonValidationRules.cs:112NotEmpty()+Must(BeAWellFormedEmail)(theEmailfactory's check) +MaximumLength(maxLength);errorCodeorcodePrefixPositiveIntRules<T>CommonValidationRules.cs:169GreaterThan(0)overintPositiveDecimalRules<T>CommonValidationRules.cs:180GreaterThan(0)overdecimalNonNegativeIntRules<T>CommonValidationRules.cs:191GreaterThanOrEqualTo(0)overintRequiredIdRules<T, TId>CommonValidationRules.cs:211NotEmpty()overTId : notnull(rejects0andGuid.Empty)OptionalPositiveIdRules<T, TId>CommonValidationRules.cs:230GreaterThan(default(TId))overTId?(null passes)StrongPasswordRules<T>CommonValidationRules.cs:248NotEmpty()+ the 8 to 128 band read fromPasswordComplexity+ fourMatches(...)over its generated regexes;errorCodeorcodePrefixThe tenth class in the file,
AbsoluteUrlRules<T>, is a Level 6 sibling (it reaches into a domain invariant) and is covered separately.Depends on: FluentValidation's
AbstractValidator<T>(NuGet, primer §3),System.Linq.Expressions.Expression<Func<T, ...>>andSystem.Globalization.CultureInfo(BCL,CommonValidationRules.cs:1-3), and the file-localOptionalErrorCodeExtensions. Two members reach further.StrongPasswordRules<T>usesPasswordComplexityfromMMCA.Common.Shared.Auth(usingatCommonValidationRules.cs:5), andEmailRules<T>delegates its format check toEmailInvariants, the check theEmailvalue object's factory runs (usingat:6), which is what lifts it to Level 4. The rest sit at the very bottom of the Application layer, which is why they carry no invariant constants and takemaxLengthas an argument. Bridged onto commands automatically byCommandRequestValidator<TCommand, TRequest>.Concept introduced, reusable FluentValidation rule fragments via
Include(). This is the first place the guide meets FluentValidation's fragment composition idiom. Rather than each validator owning a longRuleFor(...)chain, a fragment is a tinyAbstractValidator<T>whose constructor declares one field's rules, and a real validator pulls it in withInclude(new RequiredStringRules<RegisterRequest>(x => x.FirstName, "First name", NameMaxLength, codePrefix: "Register.FirstName"))(a live example atMMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:33). Two design choices make a fragment reusable across unrelated types: it is generic overT(the parent that holds the field), and it takes a selector expression rather than inheriting from that parent, so the sameEmailRules<T>validates aRegisterRequest, a bare value object, or a command with no inheritance coupling.[Rubric §24, Forms, Validation & UX Safety]assesses whether validation is defined once and reused rather than copy-pasted across create and update paths; these fragments are the framework's answer.[Rubric §1, SOLID]: each fragment has one responsibility (one field contract), so tightening the minimum password length is a one-line edit in one file rather than a search-and-replace across every module.[Rubric §11, Security]applies narrowly to the password fragment: the complexity policy is expressed once, in framework code that both apps consume, so no module can accidentally ship a weaker one.Walkthrough: the single-rule fragments are one expression body (
=>returning the configuredRuleForchain); the multi-rule ones (RequiredStringRules<T>,EmailRules<T>,StrongPasswordRules<T>) use a block body because they first callOptionalErrorCodeExtensions.EnsureOneCodeShape. Every constructor takesstring? errorCode = null; those three addstring? codePrefix = nullafter it.RequiredStringRules<T>(:79-85) takes(selector, fieldName, maxLength, errorCode, codePrefix), guards the code shape (:81) and chainsNotEmpty().WithMessage($"You must enter a {fieldName}")thenMaximumLength(maxLength), codedRequiredandMaxLengthunder a prefix (:83-84). ThefieldNameis interpolated into the human message, so one fragment yields "You must enter a Title" or "You must enter a First name". The length message is built withstring.Create(CultureInfo.InvariantCulture, $"...")(:84) so the numeric limit formats identically whatever the ambient culture is.OptionalStringRules<T>(:55-57) drops theNotEmpty; its selector isFunc<T, string?>and only the ceiling is enforced.EmailRules<T>(:121-128) puts a format rule betweenNotEmptyandMaximumLength, with the message "You must enter a valid {fieldName}" (:126). The rule is not FluentValidation'sEmailAddress()butMust(BeAWellFormedEmail)(:131-134), which trims the value and callsEmailInvariants.EnsureEmailIsValid, so an address the validator accepts is one the domain accepts too (remarks:104-110). It passes an empty value (left to the required rule) and one longer thanEmailInvariants.MaxLength(left to the length rule), so each failure is reported once. With no code supplied, the format failure answers under theEmailfactory's own code, read once from the invariant into the staticInvalidFormatCode(:118-119) so the two cannot drift; a prefix yields{codePrefix}.Required,.Invalidand.MaxLength.PositiveIntRules<T>,PositiveDecimalRules<T>andNonNegativeIntRules<T>(:102-104,:113-115,:124-126) take only(selector, fieldName, errorCode), no length, and emit one comparison rule each. The first two share the message "{fieldName} must be a positive value"; the third reads "{fieldName} must be greater than or equal to 0".RequiredIdRules<T, TId>(:142-147) is constrainedwhere TId : notnull(:143) and usesNotEmpty(). The remarks (:133-139) explain why that operator and notGreaterThan(0):NotEmptyrejects0for an integer key andGuid.Emptyfor aGuidkey, which is exactly what "no id was supplied" looks like on the wire for both shapes. Its message interpolates the field phrase verbatim into "You must specify {fieldName}", so the caller supplies the article and any qualifier, for example"an Event for the Sponsor"(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sponsors/Validation/SponsorValidationRules.cs:120).OptionalPositiveIdRules<T, TId>(:161-166) is constrainedwhere TId : struct, IComparable<TId>, IComparable(:162), takes a nullableExpression<Func<T, TId?>>selector and appliesGreaterThan(default(TId)). The remarks (:154-158) record the mechanism that keeps it cheap: FluentValidation skips a comparison rule when the nullable property holdsnull, so "must be positive when provided" needs noWhenclause and no selector recompiled per validation pass.StrongPasswordRules<T>(:250-261) takes(selector, errorCode, codePrefix): its messages are fixed strings, not parameterized by a field name. Nothing is inline: the band comes fromPasswordComplexity.MinimumLength(8) andMaximumLength(128) (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:21,:24), interpolated into the length messages under the invariant culture (:255-256), and its fourMatches(...)calls pass theUppercase,Lowercase,DigitandSpecialCharacterregex properties (:257-260). Those are[GeneratedRegex]members over the Unicode classes\p{Lu},\p{Ll},\p{Nd}and[^\p{L}\p{Nd}], each with a 1000 ms match timeout (PasswordComplexity.cs:27-42), so an accented or CJK letter counts as a letter, never as the special character. Under a prefix the seven rules answer as{codePrefix}.Required,.MinLength,.MaxLength,.Uppercase,.Lowercase,.Digitand.SpecialCharacter(:243-245). The doc comment (:241-242) states why the policy is read rather than restated:PasswordComplexityis the one definition the client form attributePasswordComplexityAttributealso evaluates, so server and client cannot disagree, andPasswordRuleParityTests(MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Ui/PasswordRuleParityTests.cs:36) compares the two verdicts.
Why it's built this way: these fragments are the DRY core of the validation story. Because they live in
MMCA.Common.Applicationand are generic, both ADC and Store inherit identical, tested field rules.[Rubric §33, Developer Experience]: a new request validator in any module reads as a short list ofInclude(...)calls, and a framework-level tightening propagates to every consumer on the next package bump instead of being missed in some forgotten validator. There is no dedicated ADR for validation; it is governed implicitly by the CQRS decorator design and the layering rules the architecture fitness tests enforce.Where it's used: modules consume them two ways. By subclassing, to bind a domain's invariant constant and error code once:
SpeakerFirstNameRules<T> : RequiredStringRules<T>(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/Validation/SpeakerValidationRules.cs:13-18),SponsorEventIdRules<T> : RequiredIdRules<T, EventIdentifierType>(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sponsors/Validation/SponsorValidationRules.cs:116-121),ProductCategoryIdRules<T> : OptionalPositiveIdRules<T, CategoryIdentifierType>(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Products/Validation/ProductValidationRules.cs:47-48), andCustomerEmailRules<T> : EmailRules<T>(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Customers/Validation/CustomerValidationRules.cs:33-34). By direct inclusion, when no domain constant is involved, which is how the framework's own auth validators use them:RegisterRequestValidatorincludesEmailRules,StrongPasswordRulesand twoRequiredStringRules, each under its ownRegister.*prefix (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:31-34),ChangePasswordRequestValidatorincludesStrongPasswordRulesfor the new password underChangePassword.NewPassword(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:23), andResetPasswordRequestValidatorincludes it with no code (ResetPasswordRequestValidator.cs:23). Whichever validator wins, it is invoked byValidatingCommandDecorator<TCommand, TResult>before the handler runs. Behavior is pinned byCommonValidationRulesTestsin group-27, which exercises the message, the optional-code path and the per-rule prefix codes (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/CommonValidationRulesTests.cs:356-421).
CommandRequestValidator<TCommand, TRequest>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommandRequestValidator.cs:30· Level 1 · class (sealed)
What it is: an auto-registered
AbstractValidator<TCommand>for any command implementingICommandWithRequest<out TRequest>. It validates the command by delegating to theIValidator<TRequest>registrations for the embedded request payload, so a module author writes rules for the request only and the command is validated for free.Depends on:
ICommandWithRequest<out TRequest>(Level 0; itsRequestproperty is the bridge, declared atMMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommandWithRequest.cs:17) and FluentValidation'sAbstractValidator<T>/IValidator<T>/SetValidator. Registered by the Application-layerDependencyInjectionscan.Concept introduced, convention-over-configuration validation.
[Rubric §2, Design Patterns]assesses whether recurring structure is handled by a named, reusable mechanism instead of repeated by hand;[Rubric §9, API & Contract Design]assesses whether input validation is applied uniformly at the edge. Most write-side commands are thin wrappers carrying a request DTO, for exampleCreateSessionCommand(CreateSessionRequest Request). Without this type a module would have to register a validator for both the request and the command. Instead the framework closesCommandRequestValidator<TCommand, TRequest>over the pair and routes command validation into the request's registered validators.Walkthrough: the class is sealed and constrained
where TCommand : ICommandWithRequest<TRequest>(:30-31), which is what makes thec.Requestselector compile. The constructor (:33-41) receivesIEnumerable<IValidator<TRequest>>by DI, null-guards it withArgumentNullException.ThrowIfNull(:35), then iteratesrequestValidators.DistinctBy(v => v.GetType())(:37) and callsRuleFor(c => c.Request).SetValidator(validator)once per surviving validator (:39). Three behaviors follow from those five lines, each documented on the class:- Every registered validator for the request runs, not just the first (
:11-17). That matches the policy the command and query decorators already apply toIValidator<TCommand>: a module that authors a validator beside a framework-supplied one expects both rule sets enforced, and honoring only the first registration would turn the rest into dead code. FluentValidation unions the failures of rules placed on one property. - Registrations are de-duplicated by runtime type (
:18-21), so a validator class registered twice (a module assembly scanned twice, say) reports each failure once rather than in duplicate. - An empty collection is not an error: the loop simply adds no rule, and the bridge is a no-op for
a request with no rules (the same point is made at
MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:217-218).
- Every registered validator for the request runs, not just the first (
Why it's built this way: it removes the most common piece of validation boilerplate (restating request rules at the command level) while staying overridable. Registration is by
TryAdd, so the convention never blocks a bespoke case. Two registration paths exist, both usingTryAddTransient: the reflection scan inScanModuleApplicationServiceswalks the module assembly for commands implementingICommandWithRequest<>, builds the closed generic and registers it (DependencyInjection.ModuleScanning.cs:86-100,TryAddTransientat:134) afterservices.AddValidatorsFromAssembly(moduleAssembly)has already picked up every hand-written validator (:117); and the explicit helperAddCommandRequestValidator<TCommand, TRequest>()(DependencyInjection.Crud.cs:220-224) does the same thing for one pair, which is how the generic update registration helpers wire their commands (:94,:150,:199). Because the explicitIValidator<TCommand>is registered first, it always wins.Where it's used: the closed generic is registered per command during module scanning. At runtime
ValidatingCommandDecorator<TCommand, TResult>injectsIEnumerable<IValidator<TCommand>>and materializes it into an array (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidatingCommandDecorator.cs:33,:36), skips validation entirely when the array is empty (:64), and otherwise runs every validator in turn (:73), accumulating failures throughValidationFailureExtensions.ToErrors(:82). Covered byCommandRequestValidatorTestsin group-27.
UsStateRules<T>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/UsAddressValidationRules.cs:18· Level 2 · class (sealed,AbstractValidator<T>subclass)
What it is: a FluentValidation fragment that requires a US address's state and accepts only a USPS region code: the 50 states, DC, the five inhabited territories and the three military regions. A sibling of
UsZipCodeRules<T>; a required US city has no fragment of its own, since it is a plainRequiredStringRules<T>(UsAddressValidationRules.cs:14-15).Depends on:
UsPostalRegionsfromMMCA.Common.Shared.ValueObjects.Contact(usingatUsAddressValidationRules.cs:3), whoseIsKnownCodeis the predicate; that Shared dependency is what lifts it to Level 2. Plus FluentValidation'sAbstractValidator<T>,CascadeModeandMust.Concept introduced: none new. The US rule classes are opt-in fragments an app composes on top of the length rules every address gets, under its own country condition, because they do not check the country (
UsAddressValidationRules.cs:12-14).[Rubric §24, Forms, Validation & UX Safety]: the accepted code list is one Shared definition, and theUsPostalRegionsremarks (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/UsPostalRegions.cs:6-11) state it lives in Shared so a UI's state picker and the server's validation accept exactly the same codes.Walkthrough: the constructor (
:33-37) is one expression body over a nullable string selector and an optionalcodePrefix.Cascade(CascadeMode.Stop)(:35) stops the chain at the first failure, so an empty state reports only "You must enter a State" (:36) rather than also failing the code check. The second rule isMust(UsPostalRegions.IsKnownCode)(:37) with the message "State must be a two-letter US state, territory or military region code".IsKnownCodetrims the value and matches it case-insensitively against aFrozenSet<string>of the codes (UsPostalRegions.cs:34-35,:43), so" ga "passes while the full name"Georgia"does not. Like its siblings it takes no singleerrorCode; with a prefix the two rules answer under{codePrefix}.Requiredand{codePrefix}.UnknownthroughOptionalErrorCodeExtensions(:36-37).Why it's built this way: validating against the same frozen set a picker renders from means a client cannot offer a value the server then rejects, and the code list changes in one file.
Where it's used: no production type in
MMCA.Common/Sourceincludes it; theUsPostalRegionsremarks name it as the server side of the shared code list (UsPostalRegions.cs:10). Composed by the test-local validator asInclude(new UsStateRules<Address>(p => p.State, codePrefix is null ? null : $"{codePrefix}.State"))(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/UsAddressValidationRulesTests.cs:95).
UsZipCodeRules<T>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/UsAddressValidationRules.cs:33· Level 2 · class (sealed,AbstractValidator<T>subclass)
What it is: a FluentValidation fragment that requires a US address's ZIP code and accepts only five digits or ZIP+4 (
12345or12345-6789). A sibling ofUsStateRules<T>.Depends on:
UsPostalRegions, whoseIsValidZipCodeis the predicate (hence Level 2), plus FluentValidation'sAbstractValidator<T>,CascadeModeandMust.Concept introduced: none new; see
UsStateRules<T>for the opt-in US fragment pattern.Walkthrough: the constructor (
:48-52) mirrorsUsStateRules<T>, including the optionalcodePrefix:Cascade(CascadeMode.Stop)(:50), thenNotEmpty()with "You must enter a Zip Code" (:51), thenMust(UsPostalRegions.IsValidZipCode)with "Zip Code must be 5 digits or ZIP+4 (12345-6789)" (:52).IsValidZipCodetrims the value and matches it against a[GeneratedRegex]^\d{5}(-\d{4})?$declaredCultureInvariant | ExplicitCapturewith a 100 ms match timeout (UsPostalRegions.cs:66-71). No singleerrorCode; with a prefix the rules answer under{codePrefix}.Requiredand{codePrefix}.Invalid(:51-52).Why it's built this way: the pattern lives beside the region codes in Shared rather than inline in the rule, so the format check is one definition any layer can call.
Where it's used: no production type in
MMCA.Common/Sourceincludes it; theUsPostalRegionsremarks name it besideUsStateRules<T>(UsPostalRegions.cs:10). Composed by the test-local validator asInclude(new UsZipCodeRules<Address>(p => p.ZipCode, codePrefix is null ? null : $"{codePrefix}.ZipCode"))(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/UsAddressValidationRulesTests.cs:96).
StateRules<T>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/AddressValidationRules.cs:62· Level 4 · class (sealed)
- What it is: a one-rule FluentValidation fragment for the optional
Statefield of a postal address. It is generic over the parent typeTand takes a selector expression, so it can be included by any validator whose model carries a state / province / region string, not only by a validator for theAddressvalue object. - Depends on: FluentValidation's
AbstractValidator<T>(NuGet, primer §3),System.Linq.Expressions.Expression<Func<T, string?>>(BCL), andAddressInvariantsfor the length ceiling (MMCA.Common.Shared.ValueObjects, imported atMMCA.Common/Source/Core/MMCA.Common.Application/Validation/AddressValidationRules.cs:4). It sits at Level 4 purely because of that constant reference: structurally it is the same fragment shape as the Level-0OptionalStringRules<T>. - Concept: the reusable rule-fragment idiom introduced by
RequiredStringRules<T>and the otherMMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.csfragments, specialised to one address field.[Rubric §1, SOLID]assesses whether each unit has one reason to change; this class has exactly one, the state field's contract, and the number that expresses that contract lives in a single shared constant rather than being retyped at each call site.[Rubric §24, Forms, Validation & UX Safety]assesses whether validation is defined once and reused across create and update paths instead of copy-pasted; including this fragment is how a request validator gets the state rule without restating it. - Walkthrough: the whole class is a constructor with an expression body
(
AddressValidationRules.cs:65-67). It takesExpression<Func<T, string?>> selectorand callsRuleFor(selector).MaximumLength(AddressInvariants.StateMaxLength). The selector is nullable (string?), which encodes the fact that state is optional onAddress(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/Address.cs:32declaresStateasstring?): there is noNotEmpty()in the chain, sonulland""both pass and only an over-length value fails. The message is built withstring.Create(CultureInfo.InvariantCulture, $"State cannot be longer than {AddressInvariants.StateMaxLength} characters")(:67), so the number a user sees is the same constant the rule enforces, and the interpolation is culture-invariant rather than dependent on the ambient culture of the validating thread. The current value of that constant is100(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:21). - Why it's built this way:
AddressInvariantsis described in its own doc comment as the single place the max lengths are shared with "EF entity configurations and FluentValidation validators" (AddressInvariants.cs:5-7). Binding the fragment to the constant rather than to a literal is what keeps the request-level rule, the domain invariant, and the column width from drifting apart. - Where it's used: composed into
AddressValidatoratAddressValidationRules.cs:20, and available for directInclude(...)by any module request validator whose DTO carries loose address fields. It is exercised directly byAddressValidationRulesTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/AddressValidationRulesTests.cs:98), which buildsnew StateRules<TestAddressModel>(p => p.State)against a model type unrelated toAddressand is therefore a live demonstration that the fragment is genuinely parent-agnostic. - Caveats / not-in-source: the rule is length-only. There is no format, enumeration, or country-aware check on the state value anywhere in this class.
ZipCodeRules<T>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/AddressValidationRules.cs:72· Level 4 · class (sealed)
- What it is: the same one-rule fragment shape as
StateRules<T>, bound to the optionalZipCodefield and its own length constant. - Depends on: FluentValidation's
AbstractValidator<T>, a nullable selector expression, andAddressInvariants. - Concept: no new concept. See
StateRules<T>for the fragment idiom and the[Rubric §24, Forms, Validation & UX Safety]treatment; this section records only what differs. - Walkthrough: the constructor body (
AddressValidationRules.cs:75-77) isRuleFor(selector).MaximumLength(AddressInvariants.ZipCodeMaxLength)with the message "Zip Code cannot be longer than {n} characters", again built throughstring.Create(CultureInfo.InvariantCulture, ...).ZipCodeMaxLengthis20(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:24), the tightest of the six address constants, and the field is nullable on the value object (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/Address.cs:36), so an absent postal code is valid. - Why it's built this way: postal-code formats differ by country, so the framework-level rule deliberately bounds length only and leaves any national format rule to the module that knows the country context. Twenty characters is wide enough for the punctuated formats used outside the United States while still bounding the string for storage and for the EF column width that shares the constant.
- Where it's used: included by
AddressValidatoratAddressValidationRules.cs:21, and covered in isolation byAddressValidationRulesTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/AddressValidationRulesTests.cs:114), which asserts a failure atZipCodeMaxLength + 1characters rather than at a hard-coded 21, so the test moves with the constant.
AddressLine1Rules<T>, AddressLine2Rules<T>, CityRules<T>, CountryRules<T>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/AddressValidationRules.cs· Level 4 · classes (sealed,AbstractValidator<T>)
What it is: four of the six per-field address rule fragments, each generic over the parent type
Tand configured with a selector expression, each pinning its length ceiling to anAddressInvariantsconstant rather than a literal. The remaining two of the six,StateRules<T>andZipCodeRules<T>, have the identical shape and are covered alongside their composite,AddressValidator.Type File:Line Rule chain Effective limit AddressLine1Rules<T>AddressValidationRules.cs:31NotEmpty()+MaximumLength(AddressInvariants.AddressLine1MaxLength)200 AddressLine2Rules<T>AddressValidationRules.cs:42MaximumLength(AddressInvariants.AddressLine2MaxLength)only200 CityRules<T>AddressValidationRules.cs:52MaximumLength(AddressInvariants.CityMaxLength)only100 CountryRules<T>AddressValidationRules.cs:82MaximumLength(AddressInvariants.CountryMaxLength)only100 The limits are
public static readonly intfields onAddressInvariants(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:12,:15,:18,:27), the same constants the EF entity configurations use, so the column width and the validator cannot drift apart.Depends on:
AddressInvariantsfromMMCA.Common.Shared.ValueObjects.Contact(imported atAddressValidationRules.cs:4), FluentValidation, andSystem.Globalization/System.Linq.Expressionsfrom the BCL (:1-2). They share the shape of the Level 0 fragments in CommonValidationRules but not an inheritance chain, and they sit at Level 4 precisely because they reference the invariant constants instead of takingmaxLengthas an argument.Concept introduced, a validation fragment bound to a domain invariant. The Level 0 fragments are policy-free: the caller supplies the number. These four bake in the canonical number by reading it from the shared invariant class, which is the right trade when the field has exactly one meaning across the whole solution (an address line is an address line in every module).
[Rubric §4, DDD]assesses whether domain rules live in one authoritative place rather than being restated per use case; here the length policy lives with theAddressvalue object's invariants and the validator merely reads it.[Rubric §24, Forms, Validation & UX Safety]: because each fragment is generic overTand selector-driven, the sameCityRules<T>validates a bareAddressvalue object and a request DTO that carries loose address fields with noAddresswrapper, a reuse the class doc calls out explicitly (AddressValidationRules.cs:9-12).[Rubric §1, SOLID](SRP): one fragment per field.Walkthrough: all four are
sealedand each constructor is a single=>expression body.AddressLine1Rules<T>(:34-37) is the only one of the six withNotEmpty(), matching the domain invariantAddressInvariants.EnsureAddressLine1IsValid, which is likewise the only field checkEnsureAddressIsValidperforms (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:34-40). Its selector is a non-nullableExpression<Func<T, string>>. The other three take a nullableExpression<Func<T, string?>>(:45,:55,:85) and enforceMaximumLengthonly, matching the fact that line 2, city and country are optional on the value object. EveryWithMessageinterpolates the actual numeric limit throughstring.Create(CultureInfo.InvariantCulture, $"...")(:37,:47,:57,:87), so the message a user sees quotes the same number the constant holds and formats culture-independently. Unlike the Level 0 fragments these constructors take noerrorCodeparameter, so their failures carry FluentValidation's default codes ("NotEmptyValidator","MaximumLengthValidator").Why it's built this way: several commands across both apps carry address fields; each can
Include(new CityRules<CreateEventRequest>(p => p.City))without copy-pasting a limit, and a change to the canonical limit flows fromAddressInvariantsinto every validator and every EF configuration at once. Splitting one address validator into six per-field fragments is what allows a DTO with only some address fields to reuse the relevant subset.Where it's used: within the current source their only production consumer is
AddressValidator, which includes each of them bound to the correspondingAddressproperty (AddressValidationRules.cs:17-19,:22). They are covered directly byAddressValidationRulesTestsin group-27 (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/AddressValidationRulesTests.cs:20,:55,:82,:130).Caveats / not-in-source: an earlier edition of this guide described these fragments as derived from
RequiredStringRules<T>. That is stale: each extendsAbstractValidator<T>directly (AddressValidationRules.cs:31-32,:42-43,:52-53,:82-83). No ADC or Store validator currently includes them directly; the reuse-outside-Addressscenario the class doc describes is supported by the design but has no consumer in the source today.
AddressValidator
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/AddressValidationRules.cs:13· Level 5 · class (sealed)
- What it is: the composite
AbstractValidator<Address>for the wholeAddressvalue object. It declares no rules of its own: its entire body is sixInclude(...)calls that bind the six per-field fragments to the sixAddressproperties. - Depends on:
Address(the validated type, imported atAddressValidationRules.cs:4) and the six Level-4 fragmentsAddressLine1Rules<T>,AddressLine2Rules<T>,CityRules<T>,StateRules<T>,ZipCodeRules<T>, andCountryRules<T>. Through those it depends transitively onAddressInvariants, and on FluentValidation. - Concept introduced, composing a value-object validator out of field fragments.
[Rubric §2, Design Patterns]assesses whether recognised patterns are applied where they earn their keep; this is composition rather than inheritance, and FluentValidation'sInclude()is the mechanism: including a validator of the same generic argument merges its rules into the including validator's rule set, so a failure surfaces with the field's own property name and message exactly as it would if the fragment ran standalone.[Rubric §24, Forms, Validation & UX Safety]assesses reuse of validation across paths: because the composite lives inMMCA.Common.Applicationrather than in a module, ADC and Store validate an address identically, and the six fragments stay independently includable for the request DTOs that carry loose address fields without anAddresswrapper (a case the class doc calls out explicitly atAddressValidationRules.cs:8-12).[Rubric §14, Testability]: because each field's rule is a separate type, a test can construct one fragment over a throwaway model, which is whatAddressValidationRulesTestsdoes before also exercising the assembled composite (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/AddressValidationRulesTests.cs:11holds the sharedAddressValidatorinstance;:144is the all-fields-valid case). - Walkthrough: the constructor (
AddressValidationRules.cs:15-23) runs six statements in property order:Include(new AddressLine1Rules<Address>(p => p.AddressLine1))(:17), thenAddressLine2Rules(:18),CityRules(:19),StateRules(:20),ZipCodeRules(:21), andCountryRules(:22). Each fragment is closed overAddressas itsT, and each selector picks the matching property.AddressLine1Rules<Address>is the only fragment in the set that contributes aNotEmpty()(AddressValidationRules.cs:36), which is what makes address line 1 the single required field of the value object; every otherIncludecontributes a max-length bound only. The class issealedand holds no state beyond the rules its constructor registers, so a call site can safely construct one per use. - Why it's built this way: the same invariants are also enforced inside the domain by
AddressInvariants.EnsureAddressIsValid(MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:35), which theAddressfactory calls. The validator exists so a bad address is rejected at the application boundary with a per-field, user-facing message instead of surfacing as a single factory failure after the command has already entered the pipeline; both paths read the same constants, so they cannot disagree on the bounds. - Where it's used: module request validators attach it with
SetValidator, notInclude, because the address is a nested object rather than a set of sibling fields on the request. The framework'sRegisterRequestValidator, registered byAddApplication()(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:16), doesRuleFor(x => x.Address).SetValidator(new AddressValidator()!).When(x => x.Address is not null)(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:36-38). Store attaches it the same way for customer creation (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Customers/UseCases/Create/CustomerCreateRequestValidator.cs:20), whileCustomerChangeAddressRequestValidator(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Customers/UseCases/ChangeAddress/CustomerChangeAddressRequestValidator.cs:17-18) attaches it with noWhenclause at all: its doc comment explains that the request'sAddressmember isrequiredand non-nullable, so FluentValidation's child-validator adapter already skips a null instance. Whichever validator wins, it reaches the runtime through the same route as every other one in this chapter: the resolvedIValidator<TCommand>set is run byValidatingCommandDecorator<TCommand, TResult>before the handler executes, and failures are mapped to domain errors byValidationFailureExtensions. - Caveats / not-in-source: the
!in the ADC and Store registration call sites suppresses a nullability warning onSetValidatorfor a nullable child property; it does not change the runtime behaviour of this validator.
AbsoluteUrlRules<T>
MMCA.Common.Application ·
MMCA.Common.Application.Validation·MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:151· Level 6 · class
- What it is: a reusable fragment for an optional URL field. It applies two rules: a maximum
length, and a check that any supplied value is an absolute
httporhttpsURI. Anullor empty value passes both. - Depends on: FluentValidation's
AbstractValidator<T>, a nullable selector expression, the internalOptionalErrorCodeExtensionshelper in the same file, andCommonInvariantsfromMMCA.Common.Domain.Invariants(imported atMMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:4), which is what puts this fragment at Level 6 while its file-mates sit at Level 0. - Concept introduced, delegating a validator predicate to the domain invariant.
[Rubric §11, Security]assesses whether untrusted input is constrained before it reaches a sink. The rule's own doc comment states the threat plainly (CommonValidationRules.cs:143-149): a length-only bound acceptsjavascript:anddata:values, and those become executable the moment a linkhrefor an imagesrcrenders them. The scheme check is therefore not cosmetic URL hygiene, it is the boundary control for stored script injection through a user-supplied link.[Rubric §9, API & Contract Design]assesses uniform, machine-readable error contracts: the fragment offers two code shapes throughOptionalErrorCodeExtensions. AnerrorCodesuch asSponsor.LogoUrl.Invalidis applied to both rules so one field answers under one code; acodePrefixsuch asSponsor.LogoUrlinstead gives each rule its own code,Sponsor.LogoUrl.MaxLengthandSponsor.LogoUrl.Invalid(the class summary,CommonValidationRules.cs:137-142). Either way a module validator composes the shared fragment rather than re-declaring its rules to get a code.[Rubric §15, Best Practices & Code Quality]: the predicate is not a second implementation of the scheme test, it calls the domain invariant, so the request-level answer and the entity-level answer cannot diverge. - Walkthrough:
- The constructor (
CommonValidationRules.cs:153-159) takes(Expression<Func<T, string?>> selector, string fieldName, int maxLength, string? errorCode = null, string? codePrefix = null). Its first statement,OptionalErrorCodeExtensions.EnsureOneCodeShape(errorCode, codePrefix)(:155), throws anArgumentExceptionwhen both are supplied, because the two describe different code shapes and accepting both would silently drop one (CommonValidationRules.cs:46-54). - It then builds a single chain:
MaximumLength(maxLength)with the interpolated "{fieldName} cannot be longer than {maxLength} characters" message, then.Must(BeAnAbsoluteHttpUrl)with "{fieldName} must be an absolute http or https URL". Each rule ends in.WithRuleCode(errorCode, codePrefix, ruleName)with"MaxLength"(:157) and"Invalid"(:158).WithRuleCode(CommonValidationRules.cs:35-37) applies{codePrefix}.{ruleName}when a prefix is given and otherwise falls through toWithOptionalErrorCode, which returns the rule untouched when the code isnull(CommonValidationRules.cs:65-67), so a caller that supplies neither keeps FluentValidation's default per-rule code. - The length message uses
string.Create(CultureInfo.InvariantCulture, ...)while the scheme message is a plain interpolation: the first embeds a number and so pins the culture, the second embeds only the field name. BeAnAbsoluteHttpUrl(:161-162) is aprivate staticpredicate that callsCommonInvariants.EnsureUrlIsWellFormed(url, "Url.Invalid", "Url.Invalid", nameof(AbsoluteUrlRules<>), "url")and returns.IsSuccess. Two details are worth reading twice. First, the invariant returns aResultand this call site discards everything except the boolean: the code, message, source, and target passed in are the invariant's own error shape, not what the user sees. The message the field actually reports is the FluentValidationWithMessagetext on:158, and the code is whatevererrorCodeorcodePrefixthe caller supplied. Second,nameof(AbsoluteUrlRules<>)uses the unbound generic form and evaluates to the plain string"AbsoluteUrlRules".- The invariant itself
(
MMCA.Common/Source/Core/MMCA.Common.Domain/Invariants/CommonInvariants.cs:293-297) passes when the string is null or empty, otherwise defers to the privateIsAbsoluteHttpUrl(CommonInvariants.cs:436-439), which requiresUri.TryCreate(url, UriKind.Absolute, out var uri)to succeed anduri.Schemeto equalUri.UriSchemeHttporUri.UriSchemeHttpsunderStringComparison.Ordinal. That is an allow-list, not a deny-list:mailto:,ftp:,file:, and any relative value are refused along withjavascript:anddata:. - Because the empty case passes, the fragment is genuinely optional-field-shaped; a caller that needs
the URL to be present pairs it with a required rule, which is what the ADC wrappers do with a
When(...)guard.
- The constructor (
- Why it's built this way: the invariant carries the doc comment explaining that length is a
separate concern to be composed via
Result.Combine(MMCA.Common/Source/Core/MMCA.Common.Domain/Invariants/CommonInvariants.cs:280-281), and this fragment is the application-layer counterpart of that composition: oneMaximumLengthrule plus one scheme rule, both reporting per field.[Rubric §26, Front-End Security]extends the same reasoning to the browser:AbsoluteUrlAttribute(MMCA.Common/Source/Presentation/MMCA.Common.UI/Validation/AbsoluteUrlAttribute.cs:26) applies the identicalUri.TryCreateplus ordinal scheme comparison (AbsoluteUrlAttribute.cs:44-46) as a DataAnnotations rule and names this class in its doc comment as the server rule it mirrors, so a form gives the verdict the API would give rather than sending the user on a round trip to find out. The two are separate implementations by necessity (the UI package does not reference the Application layer), and the parity is held by tests on both sides rather than by a shared call. - Where it's used: the ADC Conference module wraps it once per URL-bearing field, always inside a
When(x => !string.IsNullOrWhiteSpace(accessor(x)), ...)guard so a blank optional field reports nothing:SponsorLogoUrlRules<T>(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sponsors/Validation/SponsorValidationRules.cs:35),SponsorWebsiteUrlRules<T>(:65), the sponsor LinkedIn rule (:83),SpeakerLinkedInUrlRules<T>(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/Validation/SpeakerValidationRules.cs:80),SpeakerGitHubUrlRules<T>(:85) and the speaker website rule (:104),ActivityVenueUrlRules<T>(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Activities/Validation/ActivityValidationRules.cs:71), the event venue-map rule (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/Validation/EventValidationRules.cs:62),EventSponsorshipPacketUrlRules<T>(:143) and the event ticketing rule (:163), the session live and recording rules (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/Validation/SessionValidationRules.cs:71,:90), and a partner rule that passes its caller's display name and limit through (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Partners/Validation/PartnerValidationRules.cs:34). Each wrapper supplies its own module max-length constant, and none of them passes anerrorCodeor acodePrefix. Direct coverage lives inCommonValidationRulesTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/CommonValidationRulesTests.cs:585for the passing shapes,:600for rejected schemes,:612for the length bound,:529for the supplied-error-code path, and:419for the prefixedSponsor.LogoUrl.MaxLengthandSponsor.LogoUrl.Invalidcodes; the both-shapes refusal is asserted at:429against a sibling fragment). - Caveats / not-in-source: the rule constrains the scheme only. It does not check that the host resolves, that the URL is reachable, or that the target is safe to embed, and it places no restriction on host, port, or path.
ValidationFailureExtensions
MMCA.Common.Application ·
MMCA.Common.Application.Extensions·MMCA.Common/Source/Core/MMCA.Common.Application/Extensions/ValidationFailureExtensions.cs:10· Level 2 · class (static)
What it is: a static class wrapping a single C#
extension(ValidationResult)block that adds one method,ToErrors(string source), which converts FluentValidation'sValidationFailureentries into domainErrorinstances; aninternal staticToGateErrors(...)that does the same conversion for the validation gate and knows whether the validated type wraps a request DTO; and two private helpers,SynthesizeWireCodeandRuleWord, that replace a FluentValidation default (or missing) error code with a synthesized{PropertyPath}.{Rule}code. It is the one adapter that lets FluentValidation output flow into the codebase's Result pattern.Depends on:
Errorand itsErrorType.Validationclassification (imported fromMMCA.Common.Shared.Abstractions,ValidationFailureExtensions.cs:3);FluentValidation.Results(ValidationResult,ValidationFailure, NuGet,ValidationFailureExtensions.cs:2);System.Collections.Frozenfor the rule-word table (:1); LINQSelect.Concept introduced, bridging FluentValidation to the Result pattern.
[Rubric §15, Best Practices & Code Quality](assesses consistent, idiomatic conventions over one-off code; the convention here is validators produce domainErrors, never raw strings and never thrown exceptions). A FluentValidationAbstractValidator<T>produces aValidationResultwhoseErrorsare framework-specificValidationFailureobjects; everything downstream speaks inResultfailures carrying domainErrors. This extension is the only place that translation happens, so no pipeline stage, handler, or API filter is coupled to FluentValidation's failure shape. It also touches[Rubric §9, API & Contract Design](assesses uniform, standardized error responses): every failure becomes anErrorType.Validationerror, the classification the API layer maps to HTTP 400, so a validation failure looks identical at the boundary no matter which validator raised it. The same category covers the error code itself: the code is a client contract, so a rule with no explicit code answers under a stable{PropertyPath}.{Rule}code (Email.Required,Address.City.MaxLength) rather than under FluentValidation's validator class name, which the method's own remarks call an implementation detail, and a failure that carries no code at all answers under{PropertyPath}.Invalid, never under an empty code (ValidationFailureExtensions.cs:51-59).Walkthrough: the file is a static class (
ValidationFailureExtensions.cs:10) with four private members ahead of the extension block.DefaultCodeSuffix(:13) is the constant"Validator", the suffix every FluentValidation default code carries.InvalidRule(:16) is the constant"Invalid", the rule word for a failure with no more specific word or no code at all.RequestSegment(:22) is the constant"Request.", the property-path prefix a request-wrapping command's validator puts in front of every request property.RuleWords(:28-43) is an ordinalFrozenDictionary<string, string>of 13 entries mapping a default code whose class name does not read as a rule to its rule word:NotEmptyValidatorandNotNullValidatortoRequired,MaximumLengthValidatortoMaxLength,MinimumLengthValidatortoMinLength,LengthValidatorandExactLengthValidatortoLength,EmailValidatortoEmail,RegularExpressionValidatortoFormat,PredicateValidatorandAsyncPredicateValidatortoInvalid, the two between-validators toRange, andStringEnumValidatortoEnum. The singleextension(ValidationResult result)block (:45) holdsToErrors(string source)(:62), which delegates toToGateErrors(result, source, requestWrapped: false)(:63).ToGateErrors(:80) isinternal static, so only the gate insideMMCA.Common.Applicationcan passrequestWrapped: true. It declares a local functionWireCode(ValidationFailure)(:84) that forwards toSynthesizeWireCode(failure, requestWrapped), kept as one call shape so the error-resource scan recognises the code argument as a pass-through (:82-83), then projectsresult.Errorswith a LINQSelect(:86) into oneError.Validation(...)call per failure (:87), passing four arguments in order:WireCode(f)becomes the errorcode, the failure'sErrorMessagebecomes themessage, the caller-suppliedsourcebecomes thesource, and itsPropertyNamebecomes thetarget.Error.Validationis declaredValidation(string code, string message, string? source = null, string? target = null)inMMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:46, soPropertyNamelands in thetargetslot, identifying which field failed whilesourceidentifies what operation was being validated.SynthesizeWireCode(ValidationFailure, bool)(:94-121) decides the code in three branches: a null, empty or whitespace code takes the ruleInvalidRule(:98-101); a code that ends in"Validator"(ordinal) takes the rule fromRuleWord(:102-105); any other code is returned unchanged (:106-109), so a code set with.WithErrorCode(...)passes through.RuleWord(string)(:124-130) returns theRuleWordsentry if there is one, else the code with the suffix sliced off (defaultCode[..^DefaultCodeSuffix.Length],:126-128), so an unlistedGreaterThanValidatoryieldsGreaterThan; a rule left empty by the slice becomesInvalidRule(:129). For a synthesized code the path is the failure'sPropertyName, except that whenrequestWrappedis true and the path is longer than and starts with"Request."(ordinal), that leading segment is dropped (:111-118). The result is{path}.{rule}, or the bare rule when the path is empty (:120). The prefix strip touches the synthesized code only: the error'stargetstill receives the fullPropertyName, as therequestWrappedparameter documentation states (:72-78). Both methods returnIEnumerable<Error>lazily; the caller materializes it.Why it's built this way: the C#
extension(T)syntax (see primer §4) lets the conversion read as a natural method onValidationResult(result.ToErrors("X")) without subclassing FluentValidation and without a static helper every consumer must remember to reach for. It keeps the cross-cutting mapping co-located with its purpose and out of both FluentValidation andError: neither library knows the other exists. Returning a lazyIEnumerable<Error>defers the projection until the caller enumerates, which the call sites do immediately (AddRangein the validation gate, theResult.Failurefactory in the auth base). The code synthesis sits here, in the single translation point, so every validator in every module gets a stable wire code without each rule having to call.WithErrorCode(...), and a validator that does set one keeps it. TheRequest.strip exists for the same stability: a default-coded rule answers under one code (Email.Required) whether its validator ran over the bare request DTO or over theICommandWithRequest<TRequest>command that embeds it (ValidationFailureExtensions.cs:72-78). KeepingToGateErrorsinternal leaves the public surface at the singleToErrors(source)member, which never strips.Where it's used: four call sites in
MMCA.Common.Application. The internal staticValidationGate.ValidateAsync<TRequest>runs every registered validator sequentially and, for each result that is not valid, callsToGateErrorsdirectly rather than the public extension,errors.AddRange(ValidationFailureExtensions.ToGateErrors(validationResult, typeof(TRequest).Name, RequestShape<TRequest>.WrapsRequest))(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidationGate.cs:40-43, accumulating into aList<Error>?declared at:30and lazily allocated at:39). The flag comes from the private nestedRequestShape<T>, which checks once per type whetherTimplementsICommandWithRequest<>(ValidationGate.cs:57-62). BothValidatingCommandDecorator<TCommand, TResult>(ValidatingCommandDecorator.cs:46) andValidatingQueryDecorator<TQuery, TResult>(ValidatingQueryDecorator.cs:49) call that gate, which its doc comment says exists so the two cannot drift (ValidationGate.cs:8-11), sosourceis the command or query type name. The accumulate-across-all-validators shape is deliberate: the command decorator's doc comment (ValidatingCommandDecorator.cs:17-22) records that running only the first registered validator would turn the rest into silently unenforced dead code, and that collecting all of them lets the caller see every broken rule in one response instead of one per round trip. The remaining three call sites use the publicToErrorsand are inAuthenticationServiceBase<TUser>, which validates its request before touching the user store and passes the method name assource:nameof(LoginAsync)(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:168),nameof(RegisterAsync)(:305), andnameof(RefreshTokenAsync)(:405), each wrapping the result inResult.Failure<AuthenticationResponse>(...). Two checks pin the contract. The packaged architecture ruleArchitectureRules.ValidationErrorCodesAreNotValidatorNames(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Contracts/ArchitectureRules.ValidationCodes.cs:32) fails on a literal code ending inValidatorand on any read ofValidationFailure.ErrorCodeoutside this class, which it names as the one sanctioned reader (:17-18,:80).ErrorResourceCoverageTestslists"ValidationFailureExtensions.cs: WireCode(f)"as a pass-through factory site whose code the localization scan cannot resolve statically (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Localization/ErrorResourceCoverageTests.cs:47). Covered byValidationFailureExtensionsTests.Caveats / not-in-source: the default-code test is a suffix match, so an explicit
.WithErrorCode(...)value that happens to end in"Validator"is rewritten like a default one; the architecture rule above rejects such a literal, which keeps the case out of the scanned assemblies. The table covers 13 FluentValidation defaults; any other default falls back to its class name without the suffix rather than to a curated word. Separately, the nameToErrorsis reused by an unrelated extension in the gRPC layer:ResultGrpcExtensionsdeclares anextension(Metadata? trailers)block with its ownToErrors()(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:139and:159) that decodes errors out of gRPC trailers. Different receiver, different assembly, no relationship to this one.
CurrentUserServiceExtensions
MMCA.Common.Application ·
MMCA.Common.Application.Extensions·MMCA.Common/Source/Core/MMCA.Common.Application/Extensions/CurrentUserServiceExtensions.cs:9· Level 9 · class (static)
What it is: a static class holding one public constant and one
extension(ICurrentUserService)member,RequireUserId(...), which turns "who is calling, and fail if nobody is" into a single expression returning aResult<UserIdentifierType>. It is a validation-shaped caller guard: the same short-circuit-before-you-work move the validating decorators make, applied to identity rather than to command fields.Depends on:
ICurrentUserService(the extended type,CurrentUserServiceExtensions.cs:1and:14),Result,ErrorandErrorType(:2), and theUserIdentifierTypeidentifier alias (global using UserIdentifierType = int;inMMCA.Common/Source/Core/MMCA.Common.Domain/GlobalUsings.IdentifierType.cs:1, see primer). The only BCL dependency isArgumentNullException.ThrowIfNull.Concept: pushing a repeated guard into the framework rather than a base class.
[Rubric §15, Best Practices & Code Quality](assesses whether duplicated logic is consolidated where it can only be written once): the guard being replaced is the three-line read-UserId, null-check, build-a-forbidden-Error, return-a-failure block that every handler and controller protecting a per-user operation would otherwise repeat, which the type's own doc comment states atCurrentUserServiceExtensions.cs:17-19.[Rubric §11, Security](assesses that authentication and authorization decisions are made server-side and consistently): because the failure is manufactured in one place, no module can accidentally return a 200 with a default identifier for an unauthenticated caller, and no module can drift on the message.[Rubric §1, SOLID]: the guard is added by extension rather than by a handler base class, so it composes onto anyICurrentUserServiceimplementation (production service, hand-written test double, or mock) without an inheritance constraint on the consumer.Walkthrough:
AccessDeniedMessage(:12) is apublic const stringfixed to"Access denied.", documented as the message every app-side copy of this guard reports; making it a named constant is what lets a test assert the framework and the modules agree on one string. Theextension(ICurrentUserService currentUserService)block (:14) contributes the single instance methodRequireUserId(:35), whose four parameters are:code, required, the module's error code for a denied caller (for example"CheckIns.Forbidden"), kept a parameter because the code names the module and the framework cannot know that (:21-24);message, defaulting toAccessDeniedMessage(:37);errorType, defaulting toErrorType.Forbidden(:38), which is what the handler-side copies of the guard report, withErrorType.Unauthorizeddocumented as the value to pass where the edge answers 401 instead (:26-30); and an optionalsource(:39) for the calling handler's name. The body is three lines:ArgumentNullException.ThrowIfNull(currentUserService)(:41), which matters because an extension member on an interface is callable on a null reference without an NRE at the call site, then a single expression (:43-45) that pattern-matchescurrentUserService.UserId is { } userIdand returns eitherResult.Success(userId)orResult.Failure<UserIdentifierType>(new Error(code, message, errorType, source)). Theis { }property pattern is the null test and the unwrap in one step:UserIdis declaredUserIdentifierType?onICurrentUserService(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ICurrentUserService.cs:16), anduserIdis the non-nullableintbehind it. Note the failure path constructs theErrorrecord directly rather than through a factory, because the classification is a caller-supplied parameter here and the factories (Error.Forbidden,Error.UnauthorizedatMMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:91and:73) each hard-code oneErrorType.Result.Failure<T>(Error)wraps the single error into the result's error list (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Result.cs:108).Why it's built this way: the parameter set is the minimum that could not be inferred. Everything the framework can know (the message, the classification, the null handling, the
Resultshape) has a default; the one thing it cannot know, the module-scoped error code, stays required. That choice has a measurable side effect recorded in ADC's architecture fitness suite: moving"CheckIns.Forbidden"and"Points.Forbidden"out of module-sideErrorfactory calls and into arguments of this framework member made them invisible to the IL literal scan that counts ADC's error codes, one of the causes the doc comment gives for loweringErrorCatalogTests.MinimumErrorCodesfrom 66 to 57 (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Contracts/ErrorCatalogTests.cs:107-109). The floor now sits at 238 (:134) after MMCA.Common v1.328.0 taught the scan to read back the code argument of theCommonInvariants.Ensure*members and to step over computed message arguments (:118-131); that comment does not say theRequireUserIdarguments are counted again. The codes ship unchanged; only the scanner's visibility of them changed.Where it's used: six ADC Engagement handlers call it as their first statement after the null guard, then branch on
caller.IsFailureand propagatecaller.Errors:RecordSponsorVisitHandler(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/CheckIns/UseCases/RecordSponsorVisit/RecordSponsorVisitHandler.cs:53),RecordRoomCheckInHandler(.../CheckIns/UseCases/RecordRoomCheckIn/RecordRoomCheckInHandler.cs:41),ManualCheckInHandler(.../CheckIns/UseCases/ManualCheckIn/ManualCheckInHandler.cs:31),GetOrCreateMyBadgeHandler(.../CheckIns/UseCases/GetOrCreateMyBadge/GetOrCreateMyBadgeHandler.cs:28) andCheckInAttendeeHandler(.../CheckIns/UseCases/CheckInAttendee/CheckInAttendeeHandler.cs:33), all passing"CheckIns.Forbidden"; plusSetLeaderboardParticipationHandler(.../Points/UseCases/SetLeaderboardParticipation/SetLeaderboardParticipationHandler.cs:43) andGetMyPointsHandler(.../Points/UseCases/GetMyPoints/GetMyPointsHandler.cs:40) passing"Points.Forbidden". All of them take the defaults, so every one reports"Access denied."withErrorType.Forbidden. Behavior is pinned byCurrentUserServiceExtensionsTests, which asserts the success value, the default forbidden failure, the fully-overridden failure, theArgumentNullExceptionon a null service, and thatAccessDeniedMessagestill equals"Access denied."(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Extensions/CurrentUserServiceExtensionsTests.cs:16-72).Caveats / not-in-source: the name
CurrentUserServiceExtensionsis used twice in the workspace for two unrelated static classes. This one is the framework guard inMMCA.Common.Application.Extensions; ADC's Conference API ships its ownCurrentUserServiceExtensionsinMMCA.ADC.Conference.API.Authorizationwhose single member isIsPrivilegedConferenceReader(), a read visibility check over role names (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Authorization/CurrentUserServiceExtensions.cs:12-45). They share a name and an extended type and nothing else. Also noteRequireUserIdanswers only "is there an authenticated user", it makes no permission decision; capability checks stay with the[HasPermission(...)]attributes on the endpoints.
⬅ CQRS: Commands, Queries & the Decorator Pipeline • Index • Persistence & EF Core ➡