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.
Validation runs before the handler
Section titled “Validation runs before the handler”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.
Validate the value itself
Section titled “Validate the value itself”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.");}// The concept rule is synchronous; its model-pipeline bridge is inherited.// Java publishes it as an ordinary component.@Componentpublic final class AuthorNameValidator implements FundamentalsConceptValidator<AuthorName> { @Override public Class<AuthorName> getConceptType() { return AuthorName.class; }
@Override public List<ValidationResult> validate(AuthorName concept) { return concept.value().isBlank() ? List.of(ValidationResult.error("An author needs a name.")) : List.of(); }}@Componentclass AuthorNameValidator : FundamentalsConceptValidator<AuthorName> { override val conceptType: Class<AuthorName> = AuthorName::class.java
override fun validate(concept: AuthorName): List<ValidationResult> = if (concept.value().isBlank()) { listOf(ValidationResult.error("An author needs a name.")) } else { emptyList() }}import { ConceptValidator, validator } from '@cratis/arc.core';
@validator(AuthorName)export class AuthorNameValidator extends ConceptValidator<AuthorName> { constructor() { super(); this.ruleFor(name => name.value).notEmpty().withMessage('An author needs a name.'); }}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.
Validate a particular command
Section titled “Validate a particular command”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);}public final class RegisterAuthorValidator implements BlockingCommandValidator<RegisterAuthor> { @Override public Class<RegisterAuthor> getCommandType() { return RegisterAuthor.class; }
@Override public List<ValidationResult> validate(RegisterAuthor command, CommandContext context) { var name = command.name().value(); if (name.isBlank()) { return List.of(ValidationResult.error("An author needs a name.", List.of("name"))); } if (name.length() > 200) { return List.of(ValidationResult.error( "An author name is at most 200 characters.", List.of("name"))); }
return List.of(); }}
@Configurationpublic class RegisterAuthorValidation { @Bean public CommandValidator<RegisterAuthor> registerAuthorValidator() { return new BlockingCommandValidatorAdapter<>(new RegisterAuthorValidator()); }}@Componentclass RegisterAuthorValidator : CommandValidator<RegisterAuthor> { override val commandType: Class<RegisterAuthor> = RegisterAuthor::class.java
override suspend fun validate( command: RegisterAuthor, context: CommandContext ): List<ValidationResult> = when { command.name.value().isBlank() -> listOf(ValidationResult.error("An author needs a name.", listOf("name"))) command.name.value().length > 200 -> listOf(ValidationResult.error("An author name is at most 200 characters.", listOf("name"))) else -> emptyList() }}import { CommandValidator, validator } from '@cratis/arc.core';
@validator(RegisterAuthor)export class RegisterAuthorValidator extends CommandValidator<RegisterAuthor> { constructor() { super(); this.ruleFor(command => command.name).notEmpty().maxLength(200); }}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.
Reject a duplicate name
Section titled “Reject a duplicate name”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."); }}public interface AuthorsCatalog { CompletionStage<Boolean> isRegistered(AuthorName name);}
// AsyncCommandValidator returns a CompletionStage, so the lookup composes without// blocking - there is no fluent async-predicate rule to reach for.public final class RegisterAuthorValidator implements AsyncCommandValidator<RegisterAuthor> { private final AuthorsCatalog authors;
public RegisterAuthorValidator(AuthorsCatalog authors) { this.authors = authors; }
@Override public Class<RegisterAuthor> getCommandType() { return RegisterAuthor.class; }
@Override public CompletionStage<List<ValidationResult>> validate( RegisterAuthor command, CommandContext context ) { return authors.isRegistered(command.name()).thenApply(registered -> registered ? List.of(ValidationResult.error( "An author with that name is already registered.", List.of("name"))) : List.of()); }}
@Configurationpublic class RegisterAuthorValidation { @Bean public CommandValidator<RegisterAuthor> registerAuthorValidator(AuthorsCatalog authors) { return new AsyncCommandValidatorAdapter<>(new RegisterAuthorValidator(authors)); }}interface AuthorsCatalog { suspend fun isRegistered(name: AuthorName): Boolean}
@Componentclass RegisterAuthorValidator( private val authors: AuthorsCatalog) : CommandValidator<RegisterAuthor> { override val commandType: Class<RegisterAuthor> = RegisterAuthor::class.java
// validate is a suspending function, so the lookup is awaited directly - // there is no fluent async-predicate rule to reach for. override suspend fun validate( command: RegisterAuthor, context: CommandContext ): List<ValidationResult> = if (authors.isRegistered(command.name)) { listOf( ValidationResult.error( "An author with that name is already registered.", listOf("name") ) ) } else { emptyList() }}import { CommandValidator, injectable, validator } from '@cratis/arc.core';
// An abstract class, not an interface: the class itself is the service token.export abstract class AuthorsCatalog { abstract isRegistered(name: AuthorName, signal: AbortSignal): Promise<boolean>;}
@validator(RegisterAuthor)@injectable(AuthorsCatalog)export class RegisterAuthorValidator extends CommandValidator<RegisterAuthor> { constructor(authors: AuthorsCatalog) { super(); this.ruleFor(command => command.name).notEmpty().maxLength(200); this.ruleFor(command => command.name) .mustAsync(async (_name, command, signal) => !await authors.isRegistered(command.name, signal)) .withMessage('An author with that name is already registered.'); }}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.")); }}public final class SubmitOrderValidator implements BlockingCommandValidator<SubmitOrder> { private final OrderViewRepository orders;
public SubmitOrderValidator(OrderViewRepository orders) { this.orders = orders; }
@Override public Class<SubmitOrder> getCommandType() { return SubmitOrder.class; }
@Override public List<ValidationResult> validate(SubmitOrder command, CommandContext context) { var order = orders.findById(command.id()).orElse(null); if (order == null) { return List.of(ValidationResult.error("Order does not exist.", List.of("id"))); }
return order.status() == OrderStatus.READY_FOR_SUBMISSION ? List.of() : List.of(ValidationResult.error( "Only orders that are ready for submission can be submitted.", List.of("id"))); }}
@Configurationpublic class SubmitOrderValidation { @Bean public CommandValidator<SubmitOrder> submitOrderValidator(OrderViewRepository orders) { return new BlockingCommandValidatorAdapter<>(new SubmitOrderValidator(orders)); }}@Componentclass SubmitOrderValidator( private val orders: OrderViewRepository) : CommandValidator<SubmitOrder> { override val commandType: Class<SubmitOrder> = SubmitOrder::class.java
override suspend fun validate( command: SubmitOrder, context: CommandContext ): List<ValidationResult> { val order = orders.findById(command.id).orElse(null) ?: return listOf(ValidationResult.error("Order does not exist.", listOf("id")))
return if (order.status == OrderStatus.READY_FOR_SUBMISSION) { emptyList() } else { listOf( ValidationResult.error( "Only orders that are ready for submission can be submitted.", listOf("id") ) ) } }}import { CommandValidator, injectable, validator } from '@cratis/arc.core';
@validator(SubmitOrder)@injectable(OrderRepository)export class SubmitOrderValidator extends CommandValidator<SubmitOrder> { constructor(orders: OrderRepository) { super(); this.ruleFor(command => command.id) .mustAsync(async (_id, command, signal) => await orders.findById(command.id, signal) !== undefined) .withMessage('Order does not exist.'); this.ruleFor(command => command.id) .mustAsync(async (_id, command, signal) => { const order = await orders.findById(command.id, signal); return order === undefined || order.status === OrderStatus.ReadyForSubmission; }) .withMessage('Only orders that are ready for submission can be submitted.'); }}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.
Show the rejection in React
Section titled “Show the rejection in React”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.
Check the rejection paths
Section titled “Check the rejection paths”After regenerating the proxy and validation metadata for your backend, check the form with the server running:
- Leave the name blank. Expect rejection from the value rule, either in the browser when that rule was extracted or from the server.
- Register a new name. Expect the command to succeed.
- 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.
See also
Section titled “See also”- Command Validation and Validation — the full validation model.
- Make it trustworthy — the same ideas, taught step by step.
- Return a result or an error — standalone responses and the
Result<,>return shape. - Use current state in a command — injecting provider-owned state into a validator,
Provide(), orHandle().