Validation standard¶
This page sets the rules for validating domain input and configuration in ConnectSoft services and libraries. It is written for engineers who add or review validators and the code that calls them. How validation is wired (FluentValidation, DataAnnotations, options validation) is explained in Validation.
The tests for validators are covered by Validator tests, rules CS-VAL-001 to CS-VAL-005. In particular, a required Guid? identifier needs an explicit Guid.Empty check, because NotEmpty() on a Guid? accepts Guid.Empty; see CS-VAL-003. Validators that still use NotEmpty() alone on a required Guid? are listed under ENF-029.
Rules¶
CS-VAL-006: Validate domain input with ValidateAndThrowAsync at the start of the operation¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
A domain operation that validates late may already have read or written data when it finds that the input is invalid. Validating inside the try block means a validation failure is logged and counted like any other failure of the operation (CS-LOG-004), and the central exception mapping turns the ValidationException into a 400 response.
Do¶
- Inject
IValidator<TInput>into the domain service. - Call
await this.validator.ValidateAndThrowAsync(input, token).ConfigureAwait(false);as the first step of the operation, inside thetryblock and after the "started" log entry. - Pass the cancellation token.
Don't¶
- Do any work, such as reading from a repository, before validating.
- Validate outside the
tryblock, where a failure is neither logged nor counted. - Rely on automatic MVC model validation for FluentValidation validators. Validation is explicit in the domain service.
Example¶
using (this.logger.BeginScopeWithFlow(nameof(DefaultOrdersProcessor) + "/" + nameof(this.CreateOrder)))
{
try
{
ArgumentNullException.ThrowIfNull(input);
this.logger.Here(log => log.LogInformation(message: "Create Order for {OrderId} started...", input.OrderId));
await this.createOrderInputValidator.ValidateAndThrowAsync(input, token).ConfigureAwait(false);
// work
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// log, count and rethrow as in CS-LOG-004
throw;
}
}
How to check¶
In every public domain operation, ValidateAndThrowAsync is called inside the try block before the first repository, client or bus call.
CS-VAL-007: Do not call the synchronous ValidateAndThrow in asynchronous code¶
Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
The synchronous method cannot pass a cancellation token. If a validator later gains an asynchronous rule, the synchronous call throws at run time.
Do¶
- Use
ValidateAndThrowAsyncorValidateAsyncin any method that returns aTask.
Don't¶
- Call
ValidateAndThroworValidateinside an asynchronous method.
How to check¶
Search asynchronous methods in the change for .ValidateAndThrow( and .Validate(.
CS-VAL-008: Keep I/O and business decisions out of validators¶
Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
A validator checks the shape of one input: required values, lengths, ranges, formats and combinations of fields. A rule that queries a database or calls a service makes validation slow, hard to test and dependent on data that can change between validation and use. A business decision, such as whether an order can still be cancelled, belongs to the domain service, where it is checked against the current state inside the transaction.
Do¶
- Check only the input object in a validator.
- Check rules that depend on stored state in the domain service, and throw a domain exception when they fail.
Don't¶
- Inject a repository,
HttpClient, gateway client orDbContextinto a validator. - Use
MustAsyncto look up data.
Example¶
// Do: in the validator
this.RuleFor(input => input.Quantity).GreaterThan(0);
// Do: in the domain service
if (order.Status == OrderStatus.Shipped)
{
throw new OrderAlreadyShippedException(order.OrderId);
}
// Don't: in the validator
this.RuleFor(input => input.OrderId).MustAsync(async (id, token) => await repository.ExistsAsync(id, token));
How to check¶
Read the constructor parameters of new validators. A validator takes no repositories, clients or other services.
CS-VAL-009: Validate options at start-up¶
Severity: major · Applies to: service, library, template · Enforced by: manual · Status: retired
Replaced by: CS-CFG-001. Options validation is kept on the configuration page.
CS-VAL-010: Apply the same rule on the client and the server¶
Severity: minor · Applies to: service, blazor · Enforced by: manual · Status: retired
Replaced by: CS-UI-008. Validation parity between the form and the service is kept on the Blazor page.