Skip to content

Validate commands in Cratis Arc

Cratis Arc command validation rejects invalid input before the command handler runs and returns a reason the frontend can display. Use a value rule for a blank author name, a command rule for duplicate detection, and the generated proxy to carry the rejection back to the form. None of this requires event sourcing.

A failed validation rule stops the handler and produces a CommandResult containing validation messages. The proxy generator extracts supported rules for browser feedback; asynchronous lookups, custom rules, and state-dependent checks still run on the server. Client validation is not a security boundary.

Keep validators read-only. Running before the handler does not prevent a validator’s own code from causing side effects.

The C# fragments use the standalone tutorial’s domain types and imports. Choose the matching backend tab and one RegisterAuthorValidator example, not multiple competing validators. State and service examples also need the provider or application-owned collaborator described beside them.

If an author name must never be blank, put that rule on AuthorName, the value type that represents a name. Commands carrying that type can then use the same rule instead of repeating it:

public class AuthorNameValidator : ConceptValidator<AuthorName>
{
public AuthorNameValidator() =>
RuleFor(x => x.Value).NotEmpty().WithMessage("An author needs a name.");
}

View C# snippet source on GitHub

C# discovers this FluentValidation-based validator by convention. The JVM example is an imperative Spring bean: its code checks the value and returns any failures. TypeScript uses Arc’s ConceptValidator and ruleFor chains.

Browser validation depends on what the generator can extract. The imperative JVM validator above runs only on the server; becoming a Spring bean does not create a TypeScript rule. For browser-side checks on the JVM, declare literal rules with shared fluent validation. That surface supports literal string, collection, and numeric rules, not predicates or asynchronous lookups.

Use a CommandValidator<TCommand> when the rule belongs to one operation rather than to every use of a value type. This example requires a name and limits it to 200 characters:

public class RegisterAuthorValidator : CommandValidator<RegisterAuthor>
{
public RegisterAuthorValidator() =>
RuleFor(c => c.Name).NotEmpty().MaximumLength(200);
}

View C# snippet source on GitHub

C# uses FluentValidation; data annotations such as [Required] on a command record also work for lightweight cases. The JVM example returns ValidationResults from imperative checks, while TypeScript uses Arc’s fluent rules. Each backend returns server validation failures in the CommandResult envelope.

A name can be well formed and still be taken. Ask an application service whether it is already registered:

public interface IAuthorsCatalog
{
Task<bool> IsRegistered(AuthorName name);
}
public class RegisterAuthorValidator : CommandValidator<RegisterAuthor>
{
public RegisterAuthorValidator(IAuthorsCatalog authors)
{
RuleFor(c => c.Name).NotEmpty().MaximumLength(200);
RuleFor(c => c)
.MustAsync(async (command, ct) => !await authors.IsRegistered(command.Name))
.WithMessage("An author with that name is already registered.");
}
}

View C# snippet source on GitHub

This is an alternative definition of RegisterAuthorValidator, not a second class to add beside the previous example. IAuthorsCatalog / AuthorsCatalog is an application-owned contract, not an Arc interface. Supply an implementation that checks stored author names and make it available through dependency injection.

C# awaits the lookup with FluentValidation’s MustAsync; TypeScript uses Arc’s mustAsync. Kotlin calls the service directly from its suspending validate function, since its shared fluent surface has no asynchronous predicate rule. Java composes CompletionStage results through AsyncCommandValidator and AsyncCommandValidatorAdapter, without blocking. These lookups stay on the server.

On TypeScript, AuthorsCatalog is an abstract class used as a dependency-injection token, the runtime identifier for the service. Register a concrete implementation so @injectable(AuthorsCatalog) can resolve it; a TypeScript interface is erased at runtime and cannot serve as that token.

The pre-check gives the user a useful rejection, but two requests can both find no existing author before either writes. Back uniqueness with a database unique index. The validation tutorial shows the setup and explains why a racing duplicate-key exception is not automatically a field validation message. Typed handler failures can express a rejected write without implying that a returned object was persisted.

Check whether the current state allows the command

Section titled “Check whether the current state allows the command”

For an operation such as submitting an order, validate both that the order exists and that its status allows submission. In C#, a validator can take a read model, a view of stored state, as a constructor dependency. Configure provider ownership and an explicit command key so Arc knows where and how to load it.

This domain fragment assumes a keyed SubmitOrder, a provider-owned OrderReadModel, and an application OrderStatus enum:

public class SubmitOrderValidator : CommandValidator<SubmitOrder>
{
public SubmitOrderValidator(OrderReadModel? order)
{
RuleFor(_ => order).NotNull().WithMessage("Order does not exist.");
When(_ => order is not null, () =>
RuleFor(_ => order!.Status)
.Equal(OrderStatus.ReadyForSubmission)
.WithMessage("Only orders that are ready for submission can be submitted."));
}
}

View C# snippet source on GitHub

The nullable OrderReadModel lets the C# validator reject a missing order rather than fail during construction. The JVM and TypeScript examples query an application repository instead. On the JVM, provider-owned read models are resolved for provide and handle, not injected into validator constructors. TypeScript can also use readModelForValidation inside an asynchronous rule to resolve a command-keyed model.

A state check gives early feedback, not a commit-time guarantee. Another command can change the order after validation. If the condition must still hold when the write commits, enforce it through an atomic conditional write, transaction, or appropriate constraint; moving the pre-check into Handle() does not make it atomic.

With optional Chronicle integration, registered event returns can be appended and a Chronicle constraint can enforce its supported invariant at append time. Check that constraint’s scope and guarantees. Neither behavior belongs to standalone Arc.Core.

Use Execute a command from React to connect the generated command to CommandDialog and its fields. The dialog passes failed command results back to the form and stays open so the user can correct the input.

A validation message can belong to a field or to the whole command. The JVM and TypeScript duplicate examples attach their message to name, so the form can display it against that field. The C# example checks the whole command: use CommandDialog’s onValidationFailure callback to display those messages in a form-level error area. Field-only rendering will not show that command-wide rejection.

For a custom form, read validationResults, including each message’s members, from the final CommandResult. Show command-wide messages as well as field messages, and treat submission as successful only when isSuccess is true.

After regenerating the proxy and validation metadata for your backend, check the form with the server running:

  1. Leave the name blank. Expect rejection from the value rule, either in the browser when that rule was extracted or from the server.
  2. Register a new name. Expect the command to succeed.
  3. Open a new registration form and submit the same name. Expect “An author with that name is already registered.” and no additional author from that rejected command.

A friendly duplicate rejection does not prove concurrency protection. Verify the database constraint separately; the validation tutorial walks through both checks.