CommandForm server validation while editing
Cratis Arc CommandForm can check server-only rules while users edit, so they can correct a problem before submitting. Enable autoServerValidate for checks such as an email policy that reads server state. It defaults to false; submission still runs server validation when local validation passes.
Enable preflight feedback
Section titled “Enable preflight feedback”Start with the generated UpdateProfile from the backend validation example. After configuring Cratis Arc and generating the proxy, enable the check on the form that owns the edited command:
import { CommandForm, InputTextField, useIsCommandExecuting } from '@cratis/arc.react/commands';import { UpdateProfile } from './commands/UpdateProfile';
function SubmitButton() { const isExecuting = useIsCommandExecuting(); return <button type="submit" disabled={isExecuting}>{isExecuting ? 'Saving…' : 'Save'}</button>;}
export function ProfileForm() { return ( <CommandForm command={UpdateProfile} initialValues={{ name: '', email: '' }} validateOn="change" autoServerValidate autoServerValidateThrottle={500} > <InputTextField<UpdateProfile> value={c => c.name} title="Name" /> <InputTextField<UpdateProfile> value={c => c.email} title="Email" type="email" /> <SubmitButton /> </CommandForm> );}After locally valid edits settle, the form calls the generated command’s validate() and displays returned field errors. The validation request uses the command’s resolved route with /validate appended; use the generated route rather than guessing a kebab-case URL. This requires an Arc command endpoint, not an arbitrary JSON validation service.
Validation flow
Section titled “Validation flow”The typing timer waits until edits pause before sending a request. This is a debounce, despite the prop’s Throttle name: another edit clears the pending timer. The default delay is 500 ms; zero removes it on this path. Choose a longer delay for expensive checks.
Other validation paths do not use that delay. With autoServerValidate enabled, initialization, population, and eligible blur validation also call validate(). validateOnInit={false} hides initial error display but does not prevent the initialization check. validateOn controls interaction error display, while silent client validation runs on each edit. Account for these additional calls when estimating request traffic.
Add a server-only rule
Section titled “Add a server-only rule”The rule needs a command endpoint, such as UpdateProfile in Backend validation; a standalone data transfer object and validator do not create that endpoint.
Add the directory rule beside that command, then implement and register the profile-directory service for your application. Its email policy must account for the current profile and tenant, including an unchanged email on an existing profile. The fragment below supplies the validation integration, not the service implementation. For a TypeScript backend, check which rules reach the client in the generator validation reference.
using System.Threading;using System.Threading.Tasks;using Cratis.Arc.Commands;using FluentValidation;
public interface IProfileDirectory{ Task<bool> IsEmailAllowed(EmailAddress email, CancellationToken cancellationToken);}
public class UpdateProfileValidator : CommandValidator<UpdateProfile>{ public UpdateProfileValidator(IProfileDirectory profiles) { RuleFor(command => command.Name) .NotEmpty().MinimumLength(3).MaximumLength(100); RuleFor(command => command.Email) .MustAsync((command, _, cancellationToken) => profiles.IsEmailAllowed(command.Email, cancellationToken)) .WithMessage("This email cannot be used for this profile."); }}public interface ProfileDirectory { CompletionStage<Boolean> isEmailAllowed(String email);}
public final class UpdateProfileDirectoryRules implements AsyncCommandValidator<UpdateProfile> { private final ProfileDirectory profiles;
public UpdateProfileDirectoryRules(ProfileDirectory profiles) { this.profiles = profiles; }
@Override public Class<UpdateProfile> getCommandType() { return UpdateProfile.class; }
@Override public CompletionStage<List<ValidationResult>> validate( UpdateProfile command, CommandContext context ) { return profiles.isEmailAllowed(command.email()).thenApply(allowed -> allowed ? List.of() : List.of(ValidationResult.error( "This email cannot be used for this profile.", List.of("email")))); }}
@Configurationpublic class UpdateProfileValidation { @Bean public CommandValidator<UpdateProfile> updateProfileDirectoryRules(ProfileDirectory profiles) { return new AsyncCommandValidatorAdapter<>(new UpdateProfileDirectoryRules(profiles)); }}interface ProfileDirectory { suspend fun isEmailAllowed(email: String): Boolean}
@Componentclass UpdateProfileDirectoryRules( private val profiles: ProfileDirectory) : CommandValidator<UpdateProfile> { override val commandType: Class<UpdateProfile> = UpdateProfile::class.java
override suspend fun validate( command: UpdateProfile, context: CommandContext ): List<ValidationResult> = if (profiles.isEmailAllowed(command.email)) { emptyList() } else { listOf( ValidationResult.error("This email cannot be used for this profile.", listOf("email")) ) }}import { CommandValidator, injectable, validator } from '@cratis/arc.core';
export abstract class ProfileDirectory { abstract isEmailAllowed(email: EmailAddress, signal: AbortSignal): Promise<boolean>;}
@validator(UpdateProfile)@injectable(ProfileDirectory)export class UpdateProfileValidator extends CommandValidator<UpdateProfile> { constructor(profiles: ProfileDirectory) { super(); this.ruleFor(command => command.name).notEmpty().minLength(3).maxLength(100); this.ruleFor(command => command.email) .mustAsync((_email, command, signal) => profiles.isEmailAllowed(command.email, signal)) .withMessage('This email cannot be used for this profile.'); }}In C#, keep the EmailAddressValidator from the linked example: it owns the required/format rules, and this replacement validator takes over the command-level ones. Arc’s concept-aware RuleFor unwraps the property, so the three-argument MustAsync overload reads the named command.Email from the command when calling the application service. MinimumLength and MaximumLength are FluentValidation method names.
The Kotlin example uses a separate CommandValidator with a suspending validate function for the directory lookup. Keep it beside the FluentModelValidator, which projects the supported literal rules to the client; the fluent surface does not provide an asynchronous or predicate rule. There is no CancellationToken parameter: the validator runs inside the command coroutine. The Java example instead returns a CompletionStage from AsyncCommandValidator and registers it through AsyncCommandValidatorAdapter.
Either way the asynchronous directory rule remains server-side, while the name rules and supported format rules are generated for the client. No minLength, maxLength, or pattern props are supported on the built-in InputTextField.
A server preflight runs pipeline filters and validators but skips the command handler and handler-argument resolution. Validators and filters must avoid unwanted side effects and disclosing sensitive information. A successful check does not reserve an email or enforce uniqueness under concurrent writes: enforce that invariant when the application performs the write as well.
Read the response
Section titled “Read the response”Arc returns a command result with a validationResults array, not a validationErrors dictionary. This is an illustrative failure envelope; the correlation ID and rule message are example values:
{ "correlationId": "34c66385-006a-4ab6-a3f9-cb34c751ec30", "isSuccess": false, "isValid": false, "isAuthorized": true, "hasExceptions": false, "validationResults": [ { "severity": 3, "message": "This email cannot be used for this profile.", "members": ["email"], "state": null, "reason": "rule" } ], "exceptionMessages": [], "exceptionStackTrace": "", "authorizationFailureReason": "", "response": null}A failed preflight has no command response to consume; some server results omit that optional member rather than returning null. CommandForm matches members to fields and displays the first matching message by default. Use an error summary for all messages or results without members.
Limits and operating guidance
Section titled “Limits and operating guidance”Treat the displayed result as the latest applied check, not permission to submit. An older response cannot replace a newer validation result that has already been applied, but it can still appear while a newer request is pending. If your UI must tie a result to an exact edit, use the revision-guarded pattern. isExecuting reports command execution, not preflight network activity, and CommandForm exposes no validation-pending state. It cannot drive a “Checking availability” indicator.
Preflight can stop at client rules without reaching server authorization. Execution must validate and authorize again, and a request failure must not be treated as success.
The typing delay reduces traffic but does not prevent abuse. Configure ASP.NET Core rate-limiting middleware/policies or equivalent gateway controls, and verify that they cover the generated validation endpoint. Keep lookups indexed and bounded. If you cache results, include the correct tenant/user keys and expiration; cached availability still cannot enforce uniqueness at write time. Prefer submit-only validation for expensive endpoints or checks whose answers reveal private data.