Skip to content

4.3. Validation

Mikołaj Milewski edited this page Nov 12, 2026 · 1 revision

Event Validation

Stateflows validates incoming class-based event payloads before dispatching them to a Behavior. The default validator applies .NET Data Annotations, including validation attributes on the event and its properties. If validation fails, the event is not processed and its result carries validation errors.

Data Annotations by default

AddStateflowsClient registers the built-in AttributeValidator. It uses Validator.TryValidateObject with property validation enabled. For example:

using System.ComponentModel.DataAnnotations;

public sealed record CreateAccount(
    [property: Required]
    [property: EmailAddress]
    string Email);

Validation is applied to class payloads; non-class payloads bypass the validator pipeline. A class event is checked before its Behavior processor receives it. Validation results are returned as part of the send/request result rather than being delivered as a normal Behavior event.

Add custom validation

Implement IStateflowsValidator to apply application-specific rules. It receives the event and a mutable list of ValidationResult objects; return false when the event is invalid. Register the implementation on the Stateflows builder:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Stateflows;
using Stateflows.Common;

public sealed class CreateAccountValidator : IStateflowsValidator
{
    public Task<bool> ValidateAsync<TEvent>(
        TEvent @event,
        List<ValidationResult> validationResults)
    {
        if (@event is not CreateAccount request)
        {
            return Task.FromResult(true);
        }

        if (request.Email is not null &&
            request.Email.EndsWith("@blocked.example", StringComparison.OrdinalIgnoreCase))
        {
            validationResults.Add(new ValidationResult(
                "This email domain is not allowed.",
                new[] { nameof(CreateAccount.Email) }));
            return Task.FromResult(false);
        }

        return Task.FromResult(true);
    }
}

Register the validator in startup code:

services.AddStateflows(stateflows => stateflows
    .AddValidator<CreateAccountValidator>()
    .AddStateMachines(machines => machines
        .AddStateMachine<AccountWorkflow>()));

Validators are additive: the built-in Data Annotations validator and every registered IStateflowsValidator participate. See FluentValidation for the extension that adapts FluentValidation rules into Stateflows validation results.

A custom validator must tolerate malformed or missing values: a previous validator's failure does not stop the remaining validators. In this example, Data Annotations reports a missing email; the custom validator checks the domain only when an email is present.

Clone this wiki locally