↑↓ to navigate Enter to open "…" all these words ANDOR to combine

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.cs and UsAddressValidationRules.cs accept an optional machine-readable error code without any of them branching on it. It supports two code shapes: one errorCode for every rule of a field, or a codePrefix that 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 at CommonValidationRules.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 feeds ValidationFailureExtensions, which copies the failure's ErrorCode onto the domain Error.

  • Concept introduced, the machine-readable error code alongside the human message. A FluentValidation failure carries two independent strings: a ErrorMessage meant for a person and an ErrorCode meant 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: an errorCode is 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 a codePrefix under 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 outside MMCA.Common.Application; consumers reach the behavior only through the errorCode and codePrefix parameters 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 to WithOptionalErrorCode; with one it stamps WithErrorCode($"{codePrefix}.{ruleName}"), so RequiredStringRules<T> given "Register.FirstName" answers under Register.FirstName.Required and Register.FirstName.MaxLength.
    • EnsureOneCodeShape(errorCode, codePrefix) (:46-54) throws an ArgumentException naming codePrefix when 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 an errorCode calls it first.
    • WithOptionalErrorCode<T, TProperty>(rule, errorCode) (:65-67) is an expression body that reads errorCode is null ? rule : rule.WithErrorCode(errorCode). Returning the same IRuleBuilderOptions in 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-58 documents exactly that intent).
  • Why it's built this way: the alternative (an if inside 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. WithOptionalErrorCode directly in the single-code fragments (CommonValidationRules.cs:96, :173, :184, :195, :216, :235); WithRuleCode in the prefix-capable ones (:83-84, :125, :127, :157-158, :254-260) and in the two US address fragments, which pass null for the single code (UsAddressValidationRules.cs:24-25, :39-40); EnsureOneCodeShape at 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 same RuleFor chain. 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:77 NotEmpty() + MaximumLength(maxLength); errorCode or codePrefix
    OptionalStringRules<T> CommonValidationRules.cs:92 MaximumLength(maxLength) only (nullable selector, null passes)
    EmailRules<T> CommonValidationRules.cs:112 NotEmpty() + Must(BeAWellFormedEmail) (the Email factory's check) + MaximumLength(maxLength); errorCode or codePrefix
    PositiveIntRules<T> CommonValidationRules.cs:169 GreaterThan(0) over int
    PositiveDecimalRules<T> CommonValidationRules.cs:180 GreaterThan(0) over decimal
    NonNegativeIntRules<T> CommonValidationRules.cs:191 GreaterThanOrEqualTo(0) over int
    RequiredIdRules<T, TId> CommonValidationRules.cs:211 NotEmpty() over TId : notnull (rejects 0 and Guid.Empty)
    OptionalPositiveIdRules<T, TId> CommonValidationRules.cs:230 GreaterThan(default(TId)) over TId? (null passes)
    StrongPasswordRules<T> CommonValidationRules.cs:248 NotEmpty() + the 8 to 128 band read from PasswordComplexity + four Matches(...) over its generated regexes; errorCode or codePrefix

    The 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, ...>> and System.Globalization.CultureInfo (BCL, CommonValidationRules.cs:1-3), and the file-local OptionalErrorCodeExtensions. Two members reach further. StrongPasswordRules<T> uses PasswordComplexity from MMCA.Common.Shared.Auth (using at CommonValidationRules.cs:5), and EmailRules<T> delegates its format check to EmailInvariants, the check the Email value object's factory runs (using at :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 take maxLength as an argument. Bridged onto commands automatically by CommandRequestValidator<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 long RuleFor(...) chain, a fragment is a tiny AbstractValidator<T> whose constructor declares one field's rules, and a real validator pulls it in with Include(new RequiredStringRules<RegisterRequest>(x => x.FirstName, "First name", NameMaxLength, codePrefix: "Register.FirstName")) (a live example at MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:33). Two design choices make a fragment reusable across unrelated types: it is generic over T (the parent that holds the field), and it takes a selector expression rather than inheriting from that parent, so the same EmailRules<T> validates a RegisterRequest, 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 configured RuleFor chain); the multi-rule ones (RequiredStringRules<T>, EmailRules<T>, StrongPasswordRules<T>) use a block body because they first call OptionalErrorCodeExtensions.EnsureOneCodeShape. Every constructor takes string? errorCode = null; those three add string? codePrefix = null after it.

    • RequiredStringRules<T> (:79-85) takes (selector, fieldName, maxLength, errorCode, codePrefix), guards the code shape (:81) and chains NotEmpty().WithMessage($"You must enter a {fieldName}") then MaximumLength(maxLength), coded Required and MaxLength under a prefix (:83-84). The fieldName is 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 with string.Create(CultureInfo.InvariantCulture, $"...") (:84) so the numeric limit formats identically whatever the ambient culture is.
    • OptionalStringRules<T> (:55-57) drops the NotEmpty; its selector is Func<T, string?> and only the ceiling is enforced.
    • EmailRules<T> (:121-128) puts a format rule between NotEmpty and MaximumLength, with the message "You must enter a valid {fieldName}" (:126). The rule is not FluentValidation's EmailAddress() but Must(BeAWellFormedEmail) (:131-134), which trims the value and calls EmailInvariants.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 than EmailInvariants.MaxLength (left to the length rule), so each failure is reported once. With no code supplied, the format failure answers under the Email factory's own code, read once from the invariant into the static InvalidFormatCode (:118-119) so the two cannot drift; a prefix yields {codePrefix}.Required, .Invalid and .MaxLength.
    • PositiveIntRules<T>, PositiveDecimalRules<T> and NonNegativeIntRules<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 constrained where TId : notnull (:143) and uses NotEmpty(). The remarks (:133-139) explain why that operator and not GreaterThan(0): NotEmpty rejects 0 for an integer key and Guid.Empty for a Guid key, 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 constrained where TId : struct, IComparable<TId>, IComparable (:162), takes a nullable Expression<Func<T, TId?>> selector and applies GreaterThan(default(TId)). The remarks (:154-158) record the mechanism that keeps it cheap: FluentValidation skips a comparison rule when the nullable property holds null, so "must be positive when provided" needs no When clause 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 from PasswordComplexity.MinimumLength (8) and MaximumLength (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 four Matches(...) calls pass the Uppercase, Lowercase, Digit and SpecialCharacter regex 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, .Digit and .SpecialCharacter (:243-245). The doc comment (:241-242) states why the policy is read rather than restated: PasswordComplexity is the one definition the client form attribute PasswordComplexityAttribute also evaluates, so server and client cannot disagree, and PasswordRuleParityTests (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.Application and 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 of Include(...) 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), and CustomerEmailRules<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: RegisterRequestValidator includes EmailRules, StrongPasswordRules and two RequiredStringRules, each under its own Register.* prefix (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:31-34), ChangePasswordRequestValidator includes StrongPasswordRules for the new password under ChangePassword.NewPassword (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:23), and ResetPasswordRequestValidator includes it with no code (ResetPasswordRequestValidator.cs:23). Whichever validator wins, it is invoked by ValidatingCommandDecorator<TCommand, TResult> before the handler runs. Behavior is pinned by CommonValidationRulesTests in 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 implementing ICommandWithRequest<out TRequest>. It validates the command by delegating to the IValidator<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; its Request property is the bridge, declared at MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommandWithRequest.cs:17) and FluentValidation's AbstractValidator<T> / IValidator<T> / SetValidator. Registered by the Application-layer DependencyInjection scan.

  • 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 example CreateSessionCommand(CreateSessionRequest Request). Without this type a module would have to register a validator for both the request and the command. Instead the framework closes CommandRequestValidator<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 the c.Request selector compile. The constructor (:33-41) receives IEnumerable<IValidator<TRequest>> by DI, null-guards it with ArgumentNullException.ThrowIfNull (:35), then iterates requestValidators.DistinctBy(v => v.GetType()) (:37) and calls RuleFor(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 to IValidator<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).
  • 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 using TryAddTransient: the reflection scan in ScanModuleApplicationServices walks the module assembly for commands implementing ICommandWithRequest<>, builds the closed generic and registers it (DependencyInjection.ModuleScanning.cs:86-100, TryAddTransient at :134) after services.AddValidatorsFromAssembly(moduleAssembly) has already picked up every hand-written validator (:117); and the explicit helper AddCommandRequestValidator<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 explicit IValidator<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> injects IEnumerable<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 through ValidationFailureExtensions.ToErrors (:82). Covered by CommandRequestValidatorTests in 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 plain RequiredStringRules<T> (UsAddressValidationRules.cs:14-15).

  • Depends on: UsPostalRegions from MMCA.Common.Shared.ValueObjects.Contact (using at UsAddressValidationRules.cs:3), whose IsKnownCode is the predicate; that Shared dependency is what lifts it to Level 2. Plus FluentValidation's AbstractValidator<T>, CascadeMode and Must.

  • 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 the UsPostalRegions remarks (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 optional codePrefix. 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 is Must(UsPostalRegions.IsKnownCode) (:37) with the message "State must be a two-letter US state, territory or military region code". IsKnownCode trims the value and matches it case-insensitively against a FrozenSet<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 single errorCode; with a prefix the two rules answer under {codePrefix}.Required and {codePrefix}.Unknown through OptionalErrorCodeExtensions (: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/Source includes it; the UsPostalRegions remarks name it as the server side of the shared code list (UsPostalRegions.cs:10). Composed by the test-local validator as Include(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 (12345 or 12345-6789). A sibling of UsStateRules<T>.

  • Depends on: UsPostalRegions, whose IsValidZipCode is the predicate (hence Level 2), plus FluentValidation's AbstractValidator<T>, CascadeMode and Must.

  • Concept introduced: none new; see UsStateRules<T> for the opt-in US fragment pattern.

  • Walkthrough: the constructor (:48-52) mirrors UsStateRules<T>, including the optional codePrefix: Cascade(CascadeMode.Stop) (:50), then NotEmpty() with "You must enter a Zip Code" (:51), then Must(UsPostalRegions.IsValidZipCode) with "Zip Code must be 5 digits or ZIP+4 (12345-6789)" (:52). IsValidZipCode trims the value and matches it against a [GeneratedRegex] ^\d{5}(-\d{4})?$ declared CultureInvariant | ExplicitCapture with a 100 ms match timeout (UsPostalRegions.cs:66-71). No single errorCode; with a prefix the rules answer under {codePrefix}.Required and {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/Source includes it; the UsPostalRegions remarks name it beside UsStateRules<T> (UsPostalRegions.cs:10). Composed by the test-local validator as Include(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 State field of a postal address. It is generic over the parent type T and 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 the Address value object.
  • Depends on: FluentValidation's AbstractValidator<T> (NuGet, primer §3), System.Linq.Expressions.Expression<Func<T, string?>> (BCL), and AddressInvariants for the length ceiling (MMCA.Common.Shared.ValueObjects, imported at MMCA.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-0 OptionalStringRules<T>.
  • Concept: the reusable rule-fragment idiom introduced by RequiredStringRules<T> and the other MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs fragments, 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 takes Expression<Func<T, string?>> selector and calls RuleFor(selector).MaximumLength(AddressInvariants.StateMaxLength). The selector is nullable (string?), which encodes the fact that state is optional on Address (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/Address.cs:32 declares State as string?): there is no NotEmpty() in the chain, so null and "" both pass and only an over-length value fails. The message is built with string.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 is 100 (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:21).
  • Why it's built this way: AddressInvariants is 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 AddressValidator at AddressValidationRules.cs:20, and available for direct Include(...) by any module request validator whose DTO carries loose address fields. It is exercised directly by AddressValidationRulesTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/AddressValidationRulesTests.cs:98), which builds new StateRules<TestAddressModel>(p => p.State) against a model type unrelated to Address and 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 optional ZipCode field and its own length constant.
  • Depends on: FluentValidation's AbstractValidator<T>, a nullable selector expression, and AddressInvariants.
  • 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) is RuleFor(selector).MaximumLength(AddressInvariants.ZipCodeMaxLength) with the message "Zip Code cannot be longer than {n} characters", again built through string.Create(CultureInfo.InvariantCulture, ...). ZipCodeMaxLength is 20 (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 AddressValidator at AddressValidationRules.cs:21, and covered in isolation by AddressValidationRulesTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/AddressValidationRulesTests.cs:114), which asserts a failure at ZipCodeMaxLength + 1 characters 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 T and configured with a selector expression, each pinning its length ceiling to an AddressInvariants constant rather than a literal. The remaining two of the six, StateRules<T> and ZipCodeRules<T>, have the identical shape and are covered alongside their composite, AddressValidator.

    Type File:Line Rule chain Effective limit
    AddressLine1Rules<T> AddressValidationRules.cs:31 NotEmpty() + MaximumLength(AddressInvariants.AddressLine1MaxLength) 200
    AddressLine2Rules<T> AddressValidationRules.cs:42 MaximumLength(AddressInvariants.AddressLine2MaxLength) only 200
    CityRules<T> AddressValidationRules.cs:52 MaximumLength(AddressInvariants.CityMaxLength) only 100
    CountryRules<T> AddressValidationRules.cs:82 MaximumLength(AddressInvariants.CountryMaxLength) only 100

    The limits are public static readonly int fields on AddressInvariants (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: AddressInvariants from MMCA.Common.Shared.ValueObjects.Contact (imported at AddressValidationRules.cs:4), FluentValidation, and System.Globalization / System.Linq.Expressions from 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 taking maxLength as 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 the Address value object's invariants and the validator merely reads it. [Rubric §24, Forms, Validation & UX Safety]: because each fragment is generic over T and selector-driven, the same CityRules<T> validates a bare Address value object and a request DTO that carries loose address fields with no Address wrapper, a reuse the class doc calls out explicitly (AddressValidationRules.cs:9-12). [Rubric §1, SOLID] (SRP): one fragment per field.

  • Walkthrough: all four are sealed and each constructor is a single => expression body. AddressLine1Rules<T> (:34-37) is the only one of the six with NotEmpty(), matching the domain invariant AddressInvariants.EnsureAddressLine1IsValid, which is likewise the only field check EnsureAddressIsValid performs (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/AddressInvariants.cs:34-40). Its selector is a non-nullable Expression<Func<T, string>>. The other three take a nullable Expression<Func<T, string?>> (:45, :55, :85) and enforce MaximumLength only, matching the fact that line 2, city and country are optional on the value object. Every WithMessage interpolates the actual numeric limit through string.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 no errorCode parameter, 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 from AddressInvariants into 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 corresponding Address property (AddressValidationRules.cs:17-19, :22). They are covered directly by AddressValidationRulesTests in 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 extends AbstractValidator<T> directly (AddressValidationRules.cs:31-32, :42-43, :52-53, :82-83). No ADC or Store validator currently includes them directly; the reuse-outside-Address scenario 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 whole Address value object. It declares no rules of its own: its entire body is six Include(...) calls that bind the six per-field fragments to the six Address properties.
  • Depends on: Address (the validated type, imported at AddressValidationRules.cs:4) and the six Level-4 fragments AddressLine1Rules<T>, AddressLine2Rules<T>, CityRules<T>, StateRules<T>, ZipCodeRules<T>, and CountryRules<T>. Through those it depends transitively on AddressInvariants, 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's Include() 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 in MMCA.Common.Application rather 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 an Address wrapper (a case the class doc calls out explicitly at AddressValidationRules.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 what AddressValidationRulesTests does before also exercising the assembled composite (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/AddressValidationRulesTests.cs:11 holds the shared AddressValidator instance; :144 is 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), then AddressLine2Rules (:18), CityRules (:19), StateRules (:20), ZipCodeRules (:21), and CountryRules (:22). Each fragment is closed over Address as its T, and each selector picks the matching property. AddressLine1Rules<Address> is the only fragment in the set that contributes a NotEmpty() (AddressValidationRules.cs:36), which is what makes address line 1 the single required field of the value object; every other Include contributes a max-length bound only. The class is sealed and 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 the Address factory 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, not Include, because the address is a nested object rather than a set of sibling fields on the request. The framework's RegisterRequestValidator, registered by AddApplication() (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:16), does RuleFor(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), while CustomerChangeAddressRequestValidator (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Customers/UseCases/ChangeAddress/CustomerChangeAddressRequestValidator.cs:17-18) attaches it with no When clause at all: its doc comment explains that the request's Address member is required and 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 resolved IValidator<TCommand> set is run by ValidatingCommandDecorator<TCommand, TResult> before the handler executes, and failures are mapped to domain errors by ValidationFailureExtensions.
  • Caveats / not-in-source: the ! in the ADC and Store registration call sites suppresses a nullability warning on SetValidator for 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 http or https URI. A null or empty value passes both.
  • Depends on: FluentValidation's AbstractValidator<T>, a nullable selector expression, the internal OptionalErrorCodeExtensions helper in the same file, and CommonInvariants from MMCA.Common.Domain.Invariants (imported at MMCA.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 accepts javascript: and data: values, and those become executable the moment a link href or an image src renders 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 through OptionalErrorCodeExtensions. An errorCode such as Sponsor.LogoUrl.Invalid is applied to both rules so one field answers under one code; a codePrefix such as Sponsor.LogoUrl instead gives each rule its own code, Sponsor.LogoUrl.MaxLength and Sponsor.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 an ArgumentException when 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 to WithOptionalErrorCode, which returns the rule untouched when the code is null (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 a private static predicate that calls CommonInvariants.EnsureUrlIsWellFormed(url, "Url.Invalid", "Url.Invalid", nameof(AbsoluteUrlRules<>), "url") and returns .IsSuccess. Two details are worth reading twice. First, the invariant returns a Result and 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 FluentValidation WithMessage text on :158, and the code is whatever errorCode or codePrefix the 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 private IsAbsoluteHttpUrl (CommonInvariants.cs:436-439), which requires Uri.TryCreate(url, UriKind.Absolute, out var uri) to succeed and uri.Scheme to equal Uri.UriSchemeHttp or Uri.UriSchemeHttps under StringComparison.Ordinal. That is an allow-list, not a deny-list: mailto:, ftp:, file:, and any relative value are refused along with javascript: and data:.
    • 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.
  • 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: one MaximumLength rule 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 identical Uri.TryCreate plus 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 an errorCode or a codePrefix. Direct coverage lives in CommonValidationRulesTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Validation/CommonValidationRulesTests.cs:585 for the passing shapes, :600 for rejected schemes, :612 for the length bound, :529 for the supplied-error-code path, and :419 for the prefixed Sponsor.LogoUrl.MaxLength and Sponsor.LogoUrl.Invalid codes; the both-shapes refusal is asserted at :429 against 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's ValidationFailure entries into domain Error instances; an internal static ToGateErrors(...) that does the same conversion for the validation gate and knows whether the validated type wraps a request DTO; and two private helpers, SynthesizeWireCode and RuleWord, 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: Error and its ErrorType.Validation classification (imported from MMCA.Common.Shared.Abstractions, ValidationFailureExtensions.cs:3); FluentValidation.Results (ValidationResult, ValidationFailure, NuGet, ValidationFailureExtensions.cs:2); System.Collections.Frozen for the rule-word table (:1); LINQ Select.

  • 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 domain Errors, never raw strings and never thrown exceptions). A FluentValidation AbstractValidator<T> produces a ValidationResult whose Errors are framework-specific ValidationFailure objects; everything downstream speaks in Result failures carrying domain Errors. 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 an ErrorType.Validation error, 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 ordinal FrozenDictionary<string, string> of 13 entries mapping a default code whose class name does not read as a rule to its rule word: NotEmptyValidator and NotNullValidator to Required, MaximumLengthValidator to MaxLength, MinimumLengthValidator to MinLength, LengthValidator and ExactLengthValidator to Length, EmailValidator to Email, RegularExpressionValidator to Format, PredicateValidator and AsyncPredicateValidator to Invalid, the two between-validators to Range, and StringEnumValidator to Enum. The single extension(ValidationResult result) block (:45) holds ToErrors(string source) (:62), which delegates to ToGateErrors(result, source, requestWrapped: false) (:63). ToGateErrors (:80) is internal static, so only the gate inside MMCA.Common.Application can pass requestWrapped: true. It declares a local function WireCode(ValidationFailure) (:84) that forwards to SynthesizeWireCode(failure, requestWrapped), kept as one call shape so the error-resource scan recognises the code argument as a pass-through (:82-83), then projects result.Errors with a LINQ Select (:86) into one Error.Validation(...) call per failure (:87), passing four arguments in order: WireCode(f) becomes the error code, the failure's ErrorMessage becomes the message, the caller-supplied source becomes the source, and its PropertyName becomes the target. Error.Validation is declared Validation(string code, string message, string? source = null, string? target = null) in MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:46, so PropertyName lands in the target slot, identifying which field failed while source identifies what operation was being validated. SynthesizeWireCode(ValidationFailure, bool) (:94-121) decides the code in three branches: a null, empty or whitespace code takes the rule InvalidRule (:98-101); a code that ends in "Validator" (ordinal) takes the rule from RuleWord (:102-105); any other code is returned unchanged (:106-109), so a code set with .WithErrorCode(...) passes through. RuleWord(string) (:124-130) returns the RuleWords entry if there is one, else the code with the suffix sliced off (defaultCode[..^DefaultCodeSuffix.Length], :126-128), so an unlisted GreaterThanValidator yields GreaterThan; a rule left empty by the slice becomes InvalidRule (:129). For a synthesized code the path is the failure's PropertyName, except that when requestWrapped is 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's target still receives the full PropertyName, as the requestWrapped parameter documentation states (:72-78). Both methods return IEnumerable<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 on ValidationResult (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 and Error: neither library knows the other exists. Returning a lazy IEnumerable<Error> defers the projection until the caller enumerates, which the call sites do immediately (AddRange in the validation gate, the Result.Failure factory 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. The Request. 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 the ICommandWithRequest<TRequest> command that embeds it (ValidationFailureExtensions.cs:72-78). Keeping ToGateErrors internal leaves the public surface at the single ToErrors(source) member, which never strips.

  • Where it's used: four call sites in MMCA.Common.Application. The internal static ValidationGate.ValidateAsync<TRequest> runs every registered validator sequentially and, for each result that is not valid, calls ToGateErrors directly 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 a List<Error>? declared at :30 and lazily allocated at :39). The flag comes from the private nested RequestShape<T>, which checks once per type whether T implements ICommandWithRequest<> (ValidationGate.cs:57-62). Both ValidatingCommandDecorator<TCommand, TResult> (ValidatingCommandDecorator.cs:46) and ValidatingQueryDecorator<TQuery, TResult> (ValidatingQueryDecorator.cs:49) call that gate, which its doc comment says exists so the two cannot drift (ValidationGate.cs:8-11), so source is 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 public ToErrors and are in AuthenticationServiceBase<TUser>, which validates its request before touching the user store and passes the method name as source: nameof(LoginAsync) (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:168), nameof(RegisterAsync) (:305), and nameof(RefreshTokenAsync) (:405), each wrapping the result in Result.Failure<AuthenticationResponse>(...). Two checks pin the contract. The packaged architecture rule ArchitectureRules.ValidationErrorCodesAreNotValidatorNames (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Contracts/ArchitectureRules.ValidationCodes.cs:32) fails on a literal code ending in Validator and on any read of ValidationFailure.ErrorCode outside this class, which it names as the one sanctioned reader (:17-18, :80). ErrorResourceCoverageTests lists "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 by ValidationFailureExtensionsTests.

  • 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 name ToErrors is reused by an unrelated extension in the gRPC layer: ResultGrpcExtensions declares an extension(Metadata? trailers) block with its own ToErrors() (MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:139 and :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 a Result<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:1 and :14), Result, Error and ErrorType (:2), and the UserIdentifierType identifier alias (global using UserIdentifierType = int; in MMCA.Common/Source/Core/MMCA.Common.Domain/GlobalUsings.IdentifierType.cs:1, see primer). The only BCL dependency is ArgumentNullException.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 at CurrentUserServiceExtensions.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 any ICurrentUserService implementation (production service, hand-written test double, or mock) without an inheritance constraint on the consumer.

  • Walkthrough: AccessDeniedMessage (:12) is a public const string fixed 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. The extension(ICurrentUserService currentUserService) block (:14) contributes the single instance method RequireUserId (: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 to AccessDeniedMessage (:37); errorType, defaulting to ErrorType.Forbidden (:38), which is what the handler-side copies of the guard report, with ErrorType.Unauthorized documented as the value to pass where the edge answers 401 instead (:26-30); and an optional source (: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-matches currentUserService.UserId is { } userId and returns either Result.Success(userId) or Result.Failure<UserIdentifierType>(new Error(code, message, errorType, source)). The is { } property pattern is the null test and the unwrap in one step: UserId is declared UserIdentifierType? on ICurrentUserService (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ICurrentUserService.cs:16), and userId is the non-nullable int behind it. Note the failure path constructs the Error record directly rather than through a factory, because the classification is a caller-supplied parameter here and the factories (Error.Forbidden, Error.Unauthorized at MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:91 and :73) each hard-code one ErrorType. 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 Result shape) 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-side Error factory 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 lowering ErrorCatalogTests.MinimumErrorCodes from 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 the CommonInvariants.Ensure* members and to step over computed message arguments (:118-131); that comment does not say the RequireUserId arguments 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.IsFailure and propagate caller.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) and CheckInAttendeeHandler (.../CheckIns/UseCases/CheckInAttendee/CheckInAttendeeHandler.cs:33), all passing "CheckIns.Forbidden"; plus SetLeaderboardParticipationHandler (.../Points/UseCases/SetLeaderboardParticipation/SetLeaderboardParticipationHandler.cs:43) and GetMyPointsHandler (.../Points/UseCases/GetMyPoints/GetMyPointsHandler.cs:40) passing "Points.Forbidden". All of them take the defaults, so every one reports "Access denied." with ErrorType.Forbidden. Behavior is pinned by CurrentUserServiceExtensionsTests, which asserts the success value, the default forbidden failure, the fully-overridden failure, the ArgumentNullException on a null service, and that AccessDeniedMessage still equals "Access denied." (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Extensions/CurrentUserServiceExtensionsTests.cs:16-72).

  • Caveats / not-in-source: the name CurrentUserServiceExtensions is used twice in the workspace for two unrelated static classes. This one is the framework guard in MMCA.Common.Application.Extensions; ADC's Conference API ships its own CurrentUserServiceExtensions in MMCA.ADC.Conference.API.Authorization whose single member is IsPrivilegedConferenceReader(), 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 note RequireUserId answers 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 ➡