Known Limitations
These are deliberate boundaries or tracked follow-ups, not surprises.
Minimal API binding
.AddRequestValidation<T>()validates the first body argument of typeTfor backward compatibility..AddRequestValidation()validates every handler parameter with a registered validator and prefixes errors withquery.,route., orheader.when the binding attribute is present.- Complex
[FromQuery]models must be bindable by ASP.NET Core ([AsParameters]or a parseable type); the filter validates the bound object, not the raw query string. IFormFile, streams, and special framework parameters are ignored by the filter.- The non-generic filter reads handler parameter metadata and uses cached compiled delegates. Use the typed overload when an explicit, trim/AOT-friendly endpoint filter is preferred.
[SkipValidation]on a generated model or member opts out of generated rules; on a minimal API handler parameter or an MVC action parameter it skips request validation for that parameter. The attribute is also supported on DataAnnotations bridge types and properties.
Async vs sync adapters
- DataAnnotations is synchronous. Async-only validators throw
AsyncValidatorInvokedSynchronouslyExceptionon that path. - Blazor validates synchronously by default; enable
UseAsyncValidationand callJeninnetValidator.ValidateAsync()fromEditForm.OnSubmitfor async rules. - Use ASP.NET Core, Minimal API, or MediatR for server-side async rules.
- Sync
Validatenever silently skips async rules. PreValidateAsyncis stricter: synchronousValidatethrowsInvalidOperationExceptionbecause the guard cannot run.
Execution and filtering
IncludeProperties/ExcludePropertieswork on both fluent member groups and generated rules; generated rules expose their member name throughIValidationMemberRule.- Property targeting matches ordinal member names; unknown names are a no-op. Nested sub-paths
(
Address.City) are still targeted as a unit, not as individual leaf members. - Nested validation holds one collector while the outer call holds another; the inner call allocates one collector for the nesting duration. Bounded by nesting depth; a stack-based pool is future work.
- Hooks receive
RuleSetsandFailFast, but notRootDataorServiceProvider.
Emptiness and equality semantics
NotEmptydoes not treat0,false, ordefault(DateTime)as empty. It treatsnull, whitespace-only strings, empty collections, andGuid.Emptyas empty. UseNotDefault()to reject value-type defaults.EqualandNotEqualuseEqualityComparer<T>.Defaultunless the fluent overload receives an explicitIEqualityComparer<T>(for exampleStringComparer.OrdinalIgnoreCase). The attribute path always uses the default comparer.EmailAddresshas one built-in regex mode; there is no separate simple/regex switch.ScalePrecisioncounts decimal digits from the invariant string representation. SetignoreTrailingZeros(fluent orIgnoreTrailingZeros = trueon the attribute) to trim trailing fractional zeros before counting.IPAddressaccepts IPv4 and IPv6; JSON Schema represents this asanyOfwith theipv4andipv6formats. OpenAPI receives the sameanyOfshape.
Domain rules and localization packs
Jeninnet.Validation.Rules.Domainvalidates structure only. IBAN mod 97, BSN/btw-id elfproef, VAT check digits, and Egyptian national-ID date/governorate checks prove shape, not existence.- Supported countries are explicit:
VatNumber(NL,DE,FR,GB,BE),PostalCode(NL,US,DE,FR,GB,BE,EG),NationalId(NL,EG,US), and IBAN registry countries. Anything else throwsNotSupportedExceptionwhen the rule is constructed. PasswordStrengthis a policy check, not a breach-list service. The built-in common-password list is deliberately small; use a customPasswordPolicyor a custom rule for a production breach corpus. Null and empty passwords are skipped, so pair the rule withNotEmpty().- Domain rules are
serverOnlyin ClientRules because the checksum implementations are not duplicated in the browser runtime. JSON Schema/OpenAPI still expose patterns, formats, andminLength. - The built-in
nlpack is new; like the other non-English/Arabic packs, native-speaker review is welcome before the stable release.
Rule sets and failure policy
RuleSets = nulland an empty collection mean all rules, including named sets. Use["default"]to run only ungrouped rules.- The fluent per-rule
.RuleSet(...)call is terminal; apply message, condition, and other rule modifiers before it. Nested rule sets inside another rule-set callback are not independently selectable at the outer call. IncludeAllRuleSetsbypasses include selection but does not bypassExcludeRuleSets.ThrowOnFailuresis delivered after failure hooks run and is independent ofFailFast;FailFastcontrols collection, whileThrowOnFailurescontrols the final delivery.- Rule-set groups are flattened in descriptors; the original grouped rules appear with a
RuleSetsparameter instead of a syntheticRuleSetpseudo-rule.
Inheritance and runtime dispatch
SetInheritanceValidatorresolves only the exact runtime type. A runtime type that is not registered is skipped; there is no base-type or interface fallback.- The generator walks base classes for a
[Validate]type and merges rules from explicitly annotated interfaces. It does not generate validators for derived types that omit[Validate]. - Explicit interface implementations are not matched to interface members by the generator; declare the interface member publicly or repeat the rule on the class property.
- Async-only entries in an inheritance map throw
InvalidOperationExceptionon the synchronous path. UseValidateAsync.
Model shapes and date/time values
Parsed date/time literals use
CultureInfo.InvariantCulture; invalid literals fail the build withVAL0021.[FutureDate]/[PastDate]compare against UTC fromTimeProvider(ValidationCallOptions.ServiceProvider, thenTimeProvider.System). The library never converts values to the server's local time zone; normalize input at the boundary when the source is local.A null date/time value passes relative-date rules; combine with
[NotNull]when it is required.[Validate]supports classes,struct, andrecord structmodels. It does not discover validation rules on fields or static properties.Models must declare a namespace. The generator emits validators under
<model namespace>.Validators; a model in the global namespace is not supported in this preview.Open generic model declarations are rejected with
VAL0022; use a non-generic model or a fluent validator. This avoids ambiguous generated type names and DI registrations.[After]/[Before]parse against the property type (DateTime,DateTimeOffset,DateOnly, orTimeOnly) withCultureInfo.InvariantCulture.TimeOnlyaccepts clock values such as"09:30"; date-carrying strings are rejected. Invalid values produceVAL0021; there is noDateTime.Nowfallback.DateTimeOffsetvalues without an explicit offset are interpreted as UTC during generation so builds are deterministic across machines and cultures.
Collection element rules and path filtering
ForEachwith a child validator still skips null elements. UseForEachElement(...)withNotNull()when a missing element must be reported.IncludeProperties/ExcludePropertiesnormalize[0],[],[*], and custom indexers to the same collection segment. Index-specific filtering (Lines[2].Quantity) is not supported.OverrideIndexerchanges error paths and message text only. The BlazorFieldIdentifierResolverfalls back to the root model and full path when the custom indexer is not an integer; it does not throw.CollectionIndexis added to errors produced by collection element and child-element rules. It is not added to ordinary member errors.
Input sanitization
- Sanitization mutates the model in place before rules run;
Validateon a model with[Sanitize]or registered sanitizers is an explicit preprocessing contract, never silent. Sanitizers run even when rule-set filtering selects no rules, because they are preprocessing, not rules. - Members without an accessible non-init setter cannot be sanitized; the generator rejects them
at build time with
VAL0027, and fluent.Sanitize()without a setter throwsInvalidOperationExceptionat configuration time.recordpositional andinit-only members must stay immutable; sanitize a writable copy instead. - Only
stringandIList<string>members are supported; other member types are rejected withVAL0027. Collection elements cannot be sanitized insideForEachElement; sanitize the collection member itself (for example withSanitize.EachElement). - Sanitization is whitespace/casing/control-character normalization only. It is not HTML or markup sanitization, XSS protection, or output encoding; use a dedicated library for untrusted markup.
- There are no asynchronous sanitizers; sanitization is synchronous by design.
Dynamic messages and names
- Message/name factories are configuration callbacks. They should be pure and cheap; they run when an error is emitted, not during rule configuration.
- A
nullor blank factory result falls back to the static override/default message or the code-facing member name. - Dynamic
WithMessagefactories mark the error as authored, like staticWithMessage; authored messages take precedence over a message-pack template for the sameMessageKey. Dynamic messages are exported asmessageIsAuthored: truein client-rule descriptors. WithName(Func<T, string>)changes only{PropertyName}. UseOverridePropertyName(Func<T, string>)whenMemberNameitself must change.DisplayNameResolverForInstanceis process-wide when validators are created without a service provider. RegisterValidationOptionsthroughAddValidationand pass the request provider throughValidationCallOptions(ASP.NET Core filters do this automatically) to keep it container-scoped; otherwise prefer rule-level dynamic names per request.
Declarative rule metadata
- Attribute
CustomStateis a string because attribute arguments must be compile-time constants; use fluentWithStatefor arbitrary objects. - The
[Display]bridge reads onlyDisplayAttribute.NameandDisplayNameAttribute; resource types, localization, and other[Display]properties are not bridged. IValidationRuleDescriptorgainedErrorCode,DisplayName, andCustomState. This is a source-breaking contract change for external implementations; the preview package has no compatibility shim.- Metadata on generated nested/collection rules is applied to the wrapper and therefore to every child error; it does not describe the child validator's internal rules separately.
Declarative conditions and hooks
- Synchronous attribute conditions resolve to methods on the model type. They cannot reference
external services or arbitrary expressions; use fluent
Whenfor closures over captured state. - A property-level
[WhenCondition]/[UnlessCondition]overrides the class-level attribute for that property. Multiple conditions on the same scope are not combined. [RequiredIf],[RequiredUnless], and[ConditionalRange]compare one simple sibling member to a compile-time constant. Nested paths, multiple values in one attribute, and arbitrary expressions are not supported; use[WhenCondition]or fluentWhenfor those.- A value shortcut combined with
[WhenCondition]/[UnlessCondition]requires both conditions to pass. The effective method condition still follows property-over-class precedence. - Declarative
PreValidate/OnFailurehooks are static and have no async variants. Use fluentPreValidateAsync/OnFailureAsyncwhen the hook must perform I/O. - Hook errors added through
ValidationErrorCollectorare merged with rule errors, but afalsepre-validation result always stops rule evaluation.
Declarative custom validators
[CustomValidator]methods must be static, non-generic, and declared on the type passed totypeof(...). OnlyValueTask<T>async returns are supported;Task<T>is not.- The
IServiceProviderparameter receives the caller-supplied provider and can benullwhen no provider was configured. Methods that require services should accept a nullable parameter or guard before use. ValidationResulterrors with an empty member name are attributed to the property or model path; explicit member paths are preserved unchanged.- Class-level custom rules execute during validation but are not listed in the generated static descriptor. Descriptor completeness for model-level rules remains tracked as future work.
OpenAPI naming policies
The transformer resolves descriptor member names through the active JsonSerializerOptions and
JsonTypeInfo, so camelCase, snake_case, kebab-case, PascalCase, and
[JsonPropertyName] are supported. The mapping is cached per JsonTypeInfo; a descriptor member
that cannot be mapped falls back to case-insensitive matching. This conversion applies only to the
OpenAPI schema and never changes ValidationError.MemberName.
Schema mapping
requiredis a presence constraint. Non-nullable value-type members never receiverequired, even whenNotNull/NotEmptyis present; a comparison rule expresses non-default values.- Fluent
NotEmptyon a string inferstype: stringandminLength: 1when the descriptor carries the member type; generatedStringNotEmptyrules always do. IPAddressmaps toanyOfformat: "ipv4"/format: "ipv6".Enummaps tox-enum-type(the CLR enum name); the actual value list comes from the generated model schema. It is not expanded into a literalenumarray.- Conditional rules (
[RequiredIf],[RequiredUnless],[ConditionalRange], and any rule gated by a condition) are not emitted as unconditional schema constraints. JSON Schema keeps them as advisory, and the client-rules export marks themserverOnly: true; enforce them on the server. FileExtensionsuses the vendor extensionx-file-extensions, not a JSON Schema keyword.Nestedrules compose through$defs/$ref;ForEachcomposes throughitems. The child validator must expose a descriptor.Must,Custom, and conditional rules remain advisory (x-validation-rules). Conditions are opaque delegates, so they are not translated intoif/then.
Client rules runtime
ClientRulesWriter exports rule data. The companion @jeninnet/validation-client package evaluates
the supported synchronous subset and returns needsServer for conditional, nested, custom,
asynchronous, or otherwise unsupported rules. Those rules are marked serverOnly: true in the
payload. The server remains authoritative, and client messages are early feedback only.
Message precedence
WithMessage sets ValidationError.Message and marks MessageIsAuthored; authored messages win
over a message-pack template for the same MessageKey when the error is localized. Use a pack
override to change localized default text; the pack remains the fallback for non-authored errors.
DataAnnotations bridge
[JeninnetValidateProperty]runs only the named member's rules throughValidationCallOptions.IncludeProperties; it does not reimplement filtering.- When
[JeninnetValidatable]is also present, the class-level attribute wins and property-level attributes are skipped. - Unknown member names follow
IncludePropertiessemantics (a no-op), and a custom validator withoutIValidationOptionsValidator<T>throws a clearInvalidOperationException. - Nested and indexed paths must match the validator's rule-group member name; a child group is targeted as a unit.
- DataAnnotations may skip property-level attributes on null reference values; initialize the property or use class-level validation when the member can be null.
[SkipValidation]on the model type or on the validated member makes the bridge return success without running the validator; combining it with validation attributes on the same property is reported asVAL0028.- Multiple errors are joined into one DataAnnotations message.
- Reflection is used to invoke the generic validator; the bridge is not an AOT target.
- Async rules throw
AsyncValidatorInvokedSynchronouslyException; reflective invocation unwrapsTargetInvocationExceptionso callers see the original exception.
GraphQL and gRPC
- The GraphQL middleware validates provided input-object arguments on every field; scalar arguments are only validated when a validator is registered for their runtime type.
- GraphQL subscriptions are not specially handled; the same field middleware applies when they run.
- The gRPC interceptor validates unary and server-streaming calls. Client-streaming and duplex-streaming calls are not intercepted.
- gRPC status details use the
grpc-status-details-bintrailer; clients must unpackgoogle.rpc.BadRequestto read field violations. - Both packages are optional; Core and Abstractions have no GraphQL or gRPC dependency.
Localization packs
- The package ships 40 cultures; additional languages follow the contribution path and require a native-speaker review before merge.
- Culture packs preserve script and region subtags (
zh-Hans,pt-BR), while the pipeline still resolves regional requests such asfr-FRthrough the neutralfrpack. ar,he,ur, andfacontain RTL text; the package does not set UI direction.- The catalog test enforces key completeness and placeholder parity with English. A missing key or changed placeholder fails the test rather than falling back silently.
AddDefaultMessagePacksexposes a mutableIValidationMessageCatalogfor runtime additions, overrides, and removals. It is process-local and in-memory; changes do not survive a restart or propagate to other instances. Use the siblingILocalizationStorefor persistent or shared messages.AddValidationnever replacesIStringLocalizerFactory. Register anILocalizationStoreand callJeninnetLocalizationExtensions.AddLocalization(services)explicitly when you want store-backedIStringLocalizersupport.
Localization bridge
- The ASP.NET Core bridge resolves
IStringLocalizer[error.MessageKey]first, then the registered message packs, thenValidationError.Message. A missing resource is detected throughLocalizedString.ResourceNotFound, so a localizer that echoes the key does not hide the pack. IStringLocalizerhas no culture parameter. The bridge scopesCultureInfo.CurrentUICultureto the lookup and restores it immediately;CultureInfo.CurrentCultureis never changed.ForceCulturewins over an explicitly passed culture.DefaultCultureapplies only when no culture is supplied and no force culture is configured.DisableLocalizationskips only the resx source; the pack and message fallback remain.- The store-backed factory from
Jeninnet.Localization.Corerequires anILocalizationStore; register a store provider when that factory is active. AddValidation()registers the message pipeline but never activates or replaces a store-backedIStringLocalizerFactory; register the store and callAddLocalizationexplicitly when you want that bridge. This keeps container validation working when no localization provider is configured.- Resx templates use the named placeholders from the packs (
{PropertyName},{Min}, ...). PositionalIStringLocalizer[key, args]formatting is not used. - The package is not an AOT target;
IStringLocalizer/resource-manager lookups are reflection-based.
MediatR result adapters
- Adapters are separate optional packages;
Jeninnet.Validation.MediatRhas no dependency on ErrorOr, FluentResults, or CSharpFunctionalExtensions. MediatRValidationFailureStrategy.Resultrequires a configured mapper; otherwise the behavior throws an actionableInvalidOperationException.- ErrorOr and FluentResults preserve member name, severity, code, message key, parameters, and custom state in metadata. CSharpFunctionalExtensions stores only a string, so custom state and message parameters are omitted.
ThrowandContinueremain available and unchanged.
Blazor
EditContext.OnValidationRequestedis synchronous. Async validation uses the explicitJeninnetValidator.ValidateAsync()path fromEditForm.OnSubmit;EditContext.Validate()in async mode throws a guidance exception rather than blocking.EditContext.ValidateAsyncexists on .NET 11; the package’s supported async path is the explicitJeninnetValidator.ValidateAsync()call fromEditForm.OnSubmit, which also works on thenet10.0baseline.FieldChangedDebouncerequires async mode; no delay is applied by default.SkipIfModelStateValidis the double-validation toggle: it skips an unchanged, already-valid model.- The path resolver supports arrays and
IList; other collection shapes fall back to the root.
Observable UI (WPF, MAUI, Avalonia)
ObservableValidationAdapter<TModel>tracksPropertyChangedon the root model. For nested object changes, callValidate()/ValidateAsync()or forward the nested event.ValidateOnPropertyChangedandSkipIfValidrequire the model to implementINotifyPropertyChanged.MinimumSeverityfilters the errors exposed throughGetErrors/HasErrors;Validate()still returns the model's unfiltered validity.- The adapter is a decorator and does not reference a UI framework; it is not an AOT target.
Metadata and emission
- Generated descriptors are built from the runtime rule lists on first
Describe()and cached per instance. Rules added byAddCustomValidators()are included, but every validator instance pays the one-time descriptor build; this is the trade-off that keeps custom rules visible. - Rules with no metadata provider appear as
Customadvisories with aReasonandType; they are never discarded silently. UseConfigureDescriptorto add explicit metadata. - The build-time
ClientRulesCatalogcovers attribute-driven rules only. RuntimeClientRulesWriterand JSON Schema use the descriptor and include custom/configured entries. - Nested/child validators are advisory in schema/client output.
- Descriptors expose static custom state, never delegates or predicates.
- Conditional wrappers are flattened to their inner rules with
HasCondition = true; rule-set and dependent wrappers addRuleSetsandDependentparameters.
Registration and AOT
AddGeneratedValidators(assembly andType[]overloads) uses reflection and is annotated[RequiresUnreferencedCode]. Use the generated registry (AddGeneratedValidatorsFromThisAssembly) or explicit registration for trimming and Native AOT.- The generated registry is per assembly. A host that references validators from several assemblies must call each assembly's generated extension (or register those validators explicitly); there is no cross-assembly discovery.
- The generated registry is emitted only when the compilation references
Microsoft.Extensions.DependencyInjection. - Integration packages follow their host’s AOT posture; DataAnnotations, Blazor, and Observable UI are not AOT targets.
- Benchmarks and samples are outside the runtime AOT claim; the assertions package is AOT-compatible but test-only.