Create or modify a CoreEx validator in the Application layer. USE FOR: new Validator<T,TSelf> (no injection), new Validator<T> with constructor injection, AbstractValidator<T,TSelf> (FluentValidation-style), adding rules to an existing validator, nested entity/collection/dictionary validators. DO NOT USE FOR: domain invariants in aggregates, FluentValidation NuGet package, Infrastructure-layer checks.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Coreex Validator?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/avanade-coreex-validator)
---
name: coreex-validator
description: "Create or modify a CoreEx validator in the Application layer. USE FOR: new Validator<T,TSelf> (no injection), new Validator<T> with constructor injection, AbstractValidator<T,TSelf> (FluentValidation-style), adding rules to an existing validator, nested entity/collection/dictionary validators. DO NOT USE FOR: domain invariants in aggregates, FluentValidation NuGet package, Infrastructure-layer checks."
argument-hint: "Optional: contract type, validator name, list of properties to validate, any async/database checks needed"
tags: ["validators", "validation", "application-layer", "coreex", "fluent-rules", "async"]
---
<!--
AI workflow asset — dual-audience notice:
- In the Avanade/CoreEx repository: this file is the authored source. Edit it here.
- In a consumer repository: this file was generated by `dotnet new coreex-ai` (or refreshed via
`dotnet new coreex-ai --force` / the `/coreex-docs-sync` skill). Do not hand-edit it directly —
propose the change upstream in Avanade/CoreEx instead, then refresh once it is released.
-->
# CoreEx: Validator
Guides you through creating or modifying a CoreEx validator (`Application/Validators/`) for a contract or request type. Covers declarative rules, ref-data validation, async database checks, collection and dictionary validators.
Resolve requirements from the request, existing contract, and validator before asking unresolved behavioral questions one at a time.
## When to Use
- New validator for a contract or request type (no database calls needed)
- New validator that requires a repository or other Application-layer dependency
- Adding property rules or an async check to an existing validator
- Nested validator for a sub-property (`.Entity()`), a collection, or a dictionary
- Switching to FluentValidation-compatible `AbstractValidator` syntax
## When Not to Use
- Domain invariants (aggregates, entities, value objects) — those belong in the Domain layer
- External HTTP response-contract validation — use `coreex-adapter`; small client-only rules belong inline in the Infrastructure client, not `Application/Validators/`
- Other Infrastructure-level data checks that are not accessed via an Application-layer interface
- `FluentValidation` NuGet package — `AbstractValidator` here is `CoreEx.Validation.AbstractValidator`
## Quick Reference
**Decisions to resolve from the request and existing code; ask only about unresolved behavior:**
1. Does the validator need a constructor-injected dependency (e.g. a repository)? (determines base class)
2. Which properties need validation? Inspect types in the contract; ask only for missing rule requirements.
3. Are any ref-data properties required? Optional? (`.Mandatory().IsValid()` vs `.IsValid()`)
4. Are any checks async (e.g. confirming an entity exists in the database)?
5. Does the user prefer FluentValidation-style `RuleFor(x => ...)` syntax?
**Base class decision:**
| Situation | Base class | Notes |
|---|---|---|
| No injection needed | `Validator<T, TSelf>` | Exposes `Default` singleton; invoke via `.Default.ValidateAndThrowAsync(...)` |
| Constructor injection needed | `Validator<T>` | No `Default`; instantiate at the call site with already-injected dependencies: `new {Name}Validator(_dep).ValidateAndThrowAsync(...)` |
| FluentValidation-style preferred | `AbstractValidator<T, TSelf>` | `RuleFor(x => ...)` / `NotEmpty()` / `IsValid()` — still CoreEx; has `Default` |
**Key rules at a glance:**
- Configure failure metadata per call with `ValidateAndThrowAsync(value, ex => ex.ErrorCode = "invalid-request", cancellationToken)` or the equivalent `ValidateWithResultAsync` overload; never mutate shared validators or catch/rebuild exceptions just to set metadata. See the [invocation workflow](references/workflow.md#a3--invoke) for validation arguments and overload compatibility.
- For explicitly inspected validation results, use `context.ThrowOnError(ex => ex.ErrorCode = "invalid-request")`; the non-null callback configures only validation exceptions and is skipped on success. Other exception types propagate unchanged.
- Request/input validation uses field-level validation errors; aggregate/entity/value-object business invariants use business errors with domain messages/codes. Keep both checks; never derive request paths in Domain or blanket-convert business errors. See [domain invariant conventions](/.github/instructions/coreex-domain.instructions.md#invariant-failures-versus-request-validation).
- Ref-data: `.IsValid()` on the **navigation property** (`Gender`), never on `*Code` string
- Optional patch input: `.Unwrap()` validates the inner value only when specified; `.Specified()` requires presence while allowing specified-null
- `Mandatory()` on a non-nullable value type errors on `default` (`0`, `MinValue`) — use a range rule if `0` is valid
- Runtime-computed thresholds: use delegate overloads (`.LessThanOrEqualTo(_ => ...)`) — prefer over `OnValidateAsync` imperative logic
- `context.HasErrors` guard before async I/O; `context.HasError(x => x.Prop)` for per-property guards
- `context.AddError(x => x.Prop, ...)` — member-access expression, never `nameof(...)`
- Outside a validator context, prefer `ValidationException.Create<TEntity>(x => x.Address!.Street, "Street is invalid.")` for manual property errors. Property names resolve through metadata; entity access is never executed, so `!` is safe on nullable intermediates. Array/list indexes and string dictionary keys accept literals/captured locals: `addresses[0].street` / `addressesByType.home.street`. String keys follow `DictionaryKeyPolicy` (null preserves keys), matching serialized JSON and validator key/value errors; CLR paths and `GetDictionaryKey()` keep original keys. No escaping/full JSONPath support. Use `(expression, options, format, ...values)` for custom naming. No arbitrary index/key getters, calls, calculations, or intermediate casts; unlike `context.AddError`, no label/value formatting arguments or contextual naming overrides are applied.
- Conditional rules on a dependency: `.DependsOn(x => x.Other, value => predicate)` skips its attached rule when the dependency is default/invalid and otherwise runs it only when the predicate is true. Clauses guard the rule they are attached to; use another `Property(...)` call for a separate root rule chain. Use `.WhenEntity(...)` for conditions based on broader entity state.
- Message text argument is a `{2}` suffix substitution — not a full sentence; use `.Error("...")` to override the whole message
- **Always generate or update the matching `{Validator}Tests`** in `*.Test.Unit/Validators/` — cover conditional/business rules and cross-field logic thoroughly, plus a representative error/success pair for simple rules; skip dedicated boundary tests for framework-guaranteed constraints like length rules (`MaximumLength`/`MinimumLength`/`Length`/`String`)
For full workflow, rule reference, and code examples see [`references/workflow.md`](references/workflow.md).
## Key References
For aggregating manual errors outside a validator, use `MessageItem.CreateErrorMessage<TEntity>(x => x.Property, text)` and wrap the collection once. Omitted/null text infers the invalid message; `(expression, options, text)` supports custom naming. Exception/result factories share this message construction.
Expression-based exception/result factories allow an omitted/null message, defaulting to `Validation.InvalidFormat` and the leaf property's friendly metadata label: `Result.ValidationError<Person>(x => x.Name)` yields `Name is invalid.`. Terminal indexes/keys use the containing property's label. Explicit messages remain unchanged; string-property factories keep their existing semantics.
For Result-style manual errors outside a validator, use `Result.ValidationError<TEntity>(x => x.Name, "Name is invalid.")` or `Result<TValue>.ValidationError<TEntity>(...)`. These accept an expression, `LText` message (including preformatted arguments), and optional exception configuration action. For explicit serializer options or separate formatting arguments, use `ValidationException.Create<TEntity>` directly and its implicit conversion to the result type.
- [`/.github/instructions/coreex-validators.instructions.md`](/.github/instructions/coreex-validators.instructions.md) — full rule set, comparison operators, localization, DependsOn, DI registration
- [`/.github/instructions/coreex-tests.instructions.md`](/.github/instructions/coreex-tests.instructions.md) — validator unit test conventions: `Test.Scoped`, `AssertErrors`, expected message text
- Related skills: [`coreex-app-service`](../coreex-app-service/SKILL.md) (invokes the validator), [`coreex-policy`](../coreex-policy/SKILL.md) (async I/O guard sibling for checks a validator cannot do), [`coreex-contract`](../coreex-contract/SKILL.md) (the type being validated)
- Illustrative examples (CoreEx sample — not present in your project):
- [`ProductValidator` + `MovementRequestValidator`](https://github.com/Avanade/CoreEx/tree/main/samples/src/Contoso.Products.Application/Validators) — simple, plus injection + dictionary + async
- [Shopping validators](https://github.com/Avanade/CoreEx/tree/main/samples/src/Contoso.Shopping.Application/Validators) — `AbstractValidator` style, plain request validators
- [`OrderValidator`](https://github.com/Avanade/CoreEx/tree/main/samples/src/Contoso.Orders.Application/Validators) — collection validator