Validate React CommandForm input
Cratis Arc’s React CommandForm displays validation results from command rules, including supported rules generated from your backend. Define what makes a command valid on the server, then choose when the form shows feedback. HTML input attributes configure the controls but do not enforce the command’s rules.
Required fields
Section titled “Required fields”CommandForm renders <form noValidate>, so native browser constraint validation does not block submission, including submission through formRef. Set command rules for any value you need to reject.
A field’s required flag defaults to the inverse of the generated property’s isOptional descriptor. Setting required explicitly changes the control’s flag only. It does not make a command property optional or change backend validation.
| Setting | What it does | What enforces the rule |
|---|---|---|
required |
Marks the rendered control as required. | Command payload presence checks reject null/undefined for non-optional payload properties; they do not reject '', whitespace, 0, or false. |
type="email" / type="url" |
Selects the browser input type and input affordances. | An explicit email/URL command rule. |
NumberField min, max, step |
Configures the numeric control. | Command range/precision rules; typed or programmatically supplied values still need validation. |
| A required checkbox | Marks the control, but false is a present boolean value. |
A rule requiring true for consent. |
For a C# backend, use FluentValidation NotEmpty() or an appropriate [Required] rule to reject empty strings. Keep business rules on the server even when a generated client rule gives earlier feedback.
InputTextField does not expose minLength, maxLength, or pattern. Use generated rules for validation, or a custom field if the control needs those attributes. Adding them does not change the form’s noValidate behavior.
A text input can display '' when its command property is undefined. That display fallback does not assign a command value or establish a change-tracking baseline. Use initialValues for defaults you intend to submit.
Validation timing
Section titled “Validation timing”CommandForm checks validity on initialization and every field edit, even when it does not show messages. This silent validation lets the UI track validity without showing errors before the user interacts. The form starts with isValid: false until the first asynchronous check applies its result.
Choose when messages appear with validateOn. These configuration fragments belong inside a component that imports CommandForm and the generated UpdateProfile from the overview:
<CommandForm command={UpdateProfile} validateOn="blur" /><CommandForm command={UpdateProfile} validateOn="change" /><CommandForm command={UpdateProfile} validateOn="both" validateAllFieldsOnChange /><CommandForm command={UpdateProfile} validateOnInit />| Prop | Default | Effect |
|---|---|---|
validateOn |
'blur' |
Determines when interaction error messages are updated: blur, change, or both. It does not disable silent edit validation. |
validateAllFieldsOnChange |
false |
False merges only the interacted field’s displayed messages; true displays the full result. Both paths validate the command, not an isolated field rule. |
validateOnInit |
false |
Shows initialization/population errors. False hides those initial messages, not the validation work. |
autoServerValidate |
false |
Enables automatic server preflight; see Auto server validation for request paths and timing. |
Set validateAllFieldsOnChange when a rule involves several fields and editing one should update another’s message. With autoServerValidate disabled, initialization and interaction checks run client-side. Submission validates the command again and reaches the server pipeline when local checks pass.
Backend validation
Section titled “Backend validation”Add this command and validator to an already configured Arc host using the tab for your backend. The endpoint accepts a name of 3–100 characters and a nonempty, valid email address, then returns those values. It does not persist a profile or use an event store; a real update needs an explicit backend write.
using Cratis.Arc.Commands;using Cratis.Arc.Commands.ModelBound;using Cratis.Arc.Validation;using Cratis.Concepts;using FluentValidation;
namespace MyApp.Profiles;
public record ProfileName(string Value) : ConceptAs<string>(Value){ public static readonly ProfileName NotSet = new(string.Empty);}
public record EmailAddress(string Value) : ConceptAs<string>(Value){ public static readonly EmailAddress NotSet = new(string.Empty);}
public class EmailAddressValidator : ConceptValidator<EmailAddress>{ public EmailAddressValidator() => RuleFor(email => email.Value).NotEmpty().EmailAddress();}
[Command]public record UpdateProfile(ProfileName Name, EmailAddress Email){ public ProfileDetails Handle() => new(Name, Email);}
public record ProfileDetails(ProfileName Name, EmailAddress Email);
public class UpdateProfileValidator : CommandValidator<UpdateProfile>{ public UpdateProfileValidator() { RuleFor(command => command.Name).NotEmpty().MinimumLength(3).MaximumLength(100); }}import io.cratis.arc.artifacts.Command;import io.cratis.arc.validation.FluentModelValidator;
public record ProfileDetails(String name, String email) {}
public final class UpdateProfileRules extends FluentModelValidator<UpdateProfile> { public UpdateProfileRules() { super(UpdateProfile.class); ruleFor("name").notEmpty().length(3, 100); ruleFor("email").notEmpty().emailAddress(); }}
@Commandpublic record UpdateProfile(String name, String email) { public ProfileDetails handle() { return new ProfileDetails(name, email); }}package myapp.profiles
import io.cratis.arc.artifacts.Commandimport io.cratis.arc.validation.FluentModelValidator
data class ProfileDetails(val name: String, val email: String)
class UpdateProfileRules : FluentModelValidator<UpdateProfile>(UpdateProfile::class.java) { init { ruleFor("name").notEmpty().length(3, 100) ruleFor("email").notEmpty().emailAddress() }}
@Commanddata class UpdateProfile(val name: String, val email: String) { fun handle(): ProfileDetails = ProfileDetails(name, email)}import { ConceptAs, field } from '@cratis/fundamentals';import { command, CommandValidator, ConceptValidator, validator } from '@cratis/arc.core';
export class ProfileName extends ConceptAs<string> { static readonly valueType = String;}
export class EmailAddress extends ConceptAs<string> { static readonly valueType = String;}
@validator(EmailAddress)export class EmailAddressValidator extends ConceptValidator<EmailAddress> { constructor() { super(); this.ruleFor(email => email.value).notEmpty().emailAddress(); }}
export class ProfileDetails { constructor(readonly name: ProfileName, readonly email: EmailAddress) {}}
@command()export class UpdateProfile { @field(ProfileName) name!: ProfileName; @field(EmailAddress) email!: EmailAddress;
handle(): ProfileDetails { return new ProfileDetails(this.name, this.email); }}
@validator(UpdateProfile)export class UpdateProfileValidator extends CommandValidator<UpdateProfile> { constructor() { super(); this.ruleFor(command => command.name).notEmpty().minLength(3).maxLength(100); }}Each backend generates client rules from its own supported validation surface. In C#, ConceptValidator<EmailAddress> carries the email rule wherever that value type appears. CommandValidator<UpdateProfile> defines the name rule for this command. Arc’s concept-aware RuleFor unwraps ProfileName, allowing the string rules to apply. Keep each concept in its own application file; the example groups the declarations for copying.
The TypeScript backend also projects supported fluent rules from command and concept validators. Its validation generator reference identifies which rules reach the client. In these C# and TypeScript examples, the generated name and email properties are strings. The concept’s supported rules attach to email, so the React inputs do not need to convert concept objects.
Arc.Kotlin uses shared fluent validation for client rules. Its FluentModelValidator<T> accepts literal rules over string, collection, and numeric members, which is why the Kotlin and Java examples use plain strings rather than concepts. Kotlin declares the rules in a single init block; Java uses a constructor. Conditional, asynchronous, and service-dependent checks belong in ordinary server-side validators such as CommandValidator.
Generate the proxies for your backend. For C#, build in Debug with proxy generation configured. Use the generated class in the overview form: a short name or malformed email should show its rule message on blur, and a valid submission returns { name, email } to onSuccess. Only supported rules reach the client. Asynchronous service or database checks still run on the server.
Use validate() for a preflight check without running the command handler. On the C# backend, preflight also skips handler-argument resolution but still runs pipeline filters and validators. Keep those checks free of unintended side effects and sensitive diagnostic output. A preflight that stops at client validation has not checked server authorization. See backend command validation.
Form-level validation feedback
Section titled “Form-level validation feedback”Displayed validation results with no members, or with members that do not match any mounted field, appear automatically in an alert before the fields. For example, a server’s memberless Quota exceeded failure is announced rather than lost. A result matching any registered field stays with that field, including dotted paths such as email.Value; field rendering still shows its first matching message. Conditional and nested custom-layout fields are classified using committed registrations.
The summary follows the displayed command result, not silent validity checks. A custom blocked submission temporarily replaces native feedback; clearing its custom errors restores the retained native feedback. Replacing the result clears stale messages. Duplicate messages appear once, empty messages do not produce an empty alert, and messages render as text.
showErrors={false} hides automatic field, summary, and exception feedback; it does not suppress consumer-authored markup. Use validationSummaryComponent to replace or suppress only the summary, including when an application already renders a manual summary below. Validation callbacks, severity handling, validity, and safe exception feedback are unchanged.
Accessing validation state
Section titled “Accessing validation state”To build a summary, read commandResult.validationResults from a child of CommandForm. The complete component below includes results with no field member, which cannot appear beside a particular input.
showErrors={false} hides automatic field errors and form-level exception feedback without changing validation or result state. A custom exceptionDisplayComponent is not invoked in that mode. Because this summary handles validation only, provide your own safe exception feedback too.
import { CommandForm, InputTextField, useCommandFormContext } from '@cratis/arc.react/commands';import { UpdateProfile } from './commands/UpdateProfile';
function ErrorSummary() { const { commandResult } = useCommandFormContext<UpdateProfile>(); const results = commandResult?.validationResults ?? []; if (results.length === 0) return null; return ( <ul role="alert"> {results.map((result, index) => ( <li key={index}> {result.reason === 'rule' ? result.message : 'The request could not be validated. Please try again.'} </li> ))} </ul> );}
export function ProfileForm() { return ( <CommandForm command={UpdateProfile} initialValues={{ name: '', email: '' }} showErrors={false}> <InputTextField<UpdateProfile> value={c => c.name} title="Name" /> <InputTextField<UpdateProfile> value={c => c.email} title="Email" /> <ErrorSummary /> <button type="submit">Save</button> </CommandForm> );}The summary can show the full result array. For a single input, getFieldError('email') returns the first matching message, giving custom errors precedence, just like the built-in field display.
To place one field’s message yourself, render ValidationMessage from @cratis/arc.react/commands inside the form. It takes the same property accessor as the fields, reads getFieldError for that property, and renders nothing when there is no message:
<ValidationMessage<UpdateProfile> value={c => c.email} />The message renders in a <small> element colored with the --color-error CSS variable.
Keep rule messages safe for end users. The summary replaces messages whose reason is not rule with application wording. Client-side required-property checks also use reason: 'rule', with reasonDetail: 'Required'; map that detail to your own copy too, as described in validation results. Translation in the summary does not change messages rendered independently by custom fields.
Form isValid uses the latest applied silent result’s isValid flag and also requires that no nonempty custom field errors remain. It does not read the displayed commandResult.isValid or require an empty message array: non-blocking messages follow the command’s severity policy. The form’s isAuthorized checks the client identity’s roles, not server authorization.
There is no public validation-pending state. A prior verdict can remain while a newer check is in flight. Internal ordering rejects results overtaken by a later applied result, but does not reject every result for an older edit. Likewise, onFieldChange fires immediately on edits with previously displayed validation information and can fire again after blur. Its validationInfo is not a fresh asynchronous verdict to use as permission to save.
Nonempty errors from onFieldValidate and setCustomFieldError block form execution and are reported as validation failures. Clearing the last custom error restores retained native feedback; see custom-error result behavior. Calling the command directly bypasses this form-local gate. Keep business rules in command and server validation, and let execution validate again.
Validation failures and exceptions
Section titled “Validation failures and exceptions”Validation failures tell the user which values need attention; exceptions need separate, safe feedback. With showErrors enabled, CommandForm displays both when a result contains both. Field messages use errorDisplayComponent if supplied without a custom field container. A validation-only result does not produce an exception panel.
CommandForm shows exception feedback when hasExceptions is true or exceptionMessages is nonempty, even if the two disagree. It never displays the diagnostic messages or stack trace automatically. Use safe exception customization to localize the default text, An unexpected error occurred. Please try again., or replace the panel.
The onException callback depends on hasExceptions, not on whether messages exist. See exception diagnostics and display when handling results whose flag and messages disagree.
Progressive validation
Section titled “Progressive validation”Use built-in validation for ordinary feedback. If you need a Save button that waits for your own asynchronous preflight, track commandVersion, the form’s edit revision. A boolean hasChanges cannot identify later edits once it has become true.
This complete child component replaces the overview’s submit button. It waits for a pause in editing before checking, discards superseded responses, and requires a verdict for the current revision before enabling Save. Render it inside CommandForm and leave autoServerValidate off so that two preflight mechanisms do not compete.
import { useEffect, useState } from 'react';import { useCommandFormContext } from '@cratis/arc.react/commands';import { UpdateProfile } from './commands/UpdateProfile';
type Check = { revision: number; valid: boolean };
export function CheckedSubmitButton() { const { commandInstance, commandVersion, isExecuting } = useCommandFormContext<UpdateProfile>(); const [check, setCheck] = useState<Check>();
useEffect(() => { let active = true; const revision = commandVersion; const timer = setTimeout(async () => { try { const result = await commandInstance.validate(); if (active) setCheck({ revision, valid: result.isValid && result.isAuthorized && !result.hasExceptions }); } catch { if (active) setCheck({ revision, valid: false }); } }, 500); return () => { active = false; clearTimeout(timer); }; }, [commandInstance, commandVersion]);
const pending = check?.revision !== commandVersion; return ( <div> <button type="submit" disabled={pending || !check?.valid || isExecuting}>Save</button> <p role="status">{pending ? 'Checking…' : check?.valid ? 'Ready to submit.' : 'Review the values or try editing again.'}</p> </div> );}A new revision makes pending true immediately, before the effect runs. The effect’s cleanup prevents an older response from replacing the current verdict or updating state after unmount; it does not cancel an HTTP request already sent. Direct property assignments outside the form are not guaranteed to advance the revision.
Preflight can still stop at local validation and never grants permission to execute. Keyboard or programmatic submission can bypass a disabled button, so command execution must enforce the rules.
Validation results
Section titled “Validation results”validate() returns a CommandResult<TResponse> implementing ICommandResult<TResponse>. Read its outcome flags and validationResults array. The result has no errors dictionary, hasErrors() method, or getErrorsFor() method.
| Member | Meaning |
|---|---|
isSuccess, isValid, isAuthorized, hasExceptions |
Outcome flags. |
validationResults |
Array of { severity, message, members, state, reason, reasonDetail? }. |
exceptionMessages, exceptionStackTrace |
Exception diagnostics. |
authorizationFailureReason |
Authorization failure detail. |
isMissingHandler |
No server handler was registered, so execution or validation could not run. Defaults to false with older servers. |
correlationId, response |
Correlation identifier and optional typed response. |
For exact field matching outside CommandForm, filter validationResults by member name and map to messages. Account for casing/nested paths in your own renderer; within the form prefer getFieldError() for its field-matching behavior.
Validation metadata
Section titled “Validation metadata”CommandFormState (the onStateChange argument), the context and the formRef handle expose an optional validation snapshot with a client and a server channel. It describes what validation concluded and how fresh that is; isValid and submission are unchanged.
| Member | Meaning |
|---|---|
pending |
A validation is in flight or, for the server, waiting behind autoServerValidateThrottle. |
freshness |
unvalidated, stale (the verdict describes earlier values) or current. |
verdict |
unknown, valid, invalid or error (the attempt failed - exception, validatorFailed, dependencyUnavailable, malformedRequest, frameworkFailure). A command without a server handler reports unknown. |
validatedVersion |
The revision of the form values the verdict describes. |
notRunReason |
unauthorized when the server refused before any rule ran, missingHandler when no server handler was registered, serverValidationDisabled when autoServerValidate is off. |
A missing handler leaves the server channel unvalidated, with no validatedVersion, just like an unauthorized attempt. The result’s exception diagnostics and HTTP status are unchanged.
A current, valid verdict is a preflight: it never guarantees the command will execute successfully. A result is attributed to the server channel only when the server could have produced it; when client rules reject, Command.validate() answers locally and that result is recorded as the client’s.