Skip to content

CommandDialog responses and field validation

Use CommandDialog callbacks to act on a Cratis Arc command’s response, explain a failure, or check a field as the user edits it. Keep values needed for validation in the form before confirmation; use onBeforeExecute for final transformations, not to supply missing required input.

The snippets assume generated command proxies such as CreateUser, and app helpers such as showNotification and navigate. If you still need to open the dialog and return its result to the calling page, start with the basic example on CommandDialog.

Pass the backend response type as the second type argument when you need values from a successful command. In this example, onSuccess uses the new user’s id to navigate to their page. onFailed receives the full failure result; the other callbacks let the app react to specific failure conditions.

import { CommandDialog } from '@cratis/components/CommandDialog';
type CreateUserResponse = {
userId: string;
username: string;
message: string;
};
<CommandDialog<CreateUser, CreateUserResponse>
command={CreateUser}
title="Create User"
onSuccess={(response) => {
// Handle successful creation - response is fully typed
console.log(`User created with ID: ${response.userId}`);
showNotification(response.message);
navigate(`/users/${response.userId}`);
}}
onFailed={(commandResult) => {
// Handle any failure - includes all failure details
console.error('Command failed:', commandResult);
}}
onException={(messages, stackTrace) => {
// Handle exceptions specifically
console.error('Exception occurred:', messages.join(', '));
console.error('Stack trace:', stackTrace);
}}
onUnauthorized={() => {
// Handle authorization failures
showNotification('You are not authorized to perform this action');
navigate('/login');
}}
onValidationFailure={(validationResults) => {
// Handle validation failures
const errors = validationResults.map(r => r.message).join(', ');
showNotification(`Validation failed: ${errors}`);
}}
>
<InputTextField<CreateUser> value={(c) => c.username} title="Username" />
</CommandDialog>

Success and failure take separate paths. On success, the dialog awaits onSuccess(response) and then onConfirm(), or onClose(DialogResult.Ok) if onConfirm is absent, to decide whether to close. To return the response to the calling page, call closeDialog(DialogResult.Ok, response) from onSuccess; the automatic close does not pass a value.

On failure, the dialog awaits callbacks in this order, skipping any that do not match the result:

  1. onFailed(commandResult) for every unsuccessful result.
  2. onException(messages, stackTrace) when commandResult.hasExceptions is true.
  3. onUnauthorized() when commandResult.isAuthorized is false.
  4. onValidationFailure(validationResults) when commandResult.isValid is false.

A validation failure therefore calls onFailed before onValidationFailure, not onSuccess. After the failure callbacks finish, the dialog applies the result to the form so matching fields show the server’s validation messages. It does not automatically close on failure. See Dialog Callbacks for the close decision and Confirm before executing for guard failures before a command runs.

The busy state ends as soon as the command settles, before any result callback runs. The busy-state disabling is therefore lifted (normal validity rules still apply to confirm) while onSuccess, onFailed and the other result callbacks are awaited, so a slow callback should show its own progress if it needs to.

The command has already run by then, and a callback cannot undo it. If a callback throws or returns a rejected promise, the dialog stops at that point:

  • Later callbacks in the same sequence do not run. A rejected onFailed skips onException, onUnauthorized and onValidationFailure; a rejected onSuccess skips onConfirm and the onClose fallback.
  • After a failed command, the result is not applied to the form, so server validation messages do not appear on the fields.
  • The dialog does not close automatically and does not announce a refusal. It stays open with its current values.

The command’s outcome is unchanged: a successful command stays successful even when onSuccess rejects. Catch errors inside your callbacks when the rest of the sequence must still run, and report them in your own UI.

When a submit is refused with validation results, the dialog announces a summary in its polite live region and moves focus to the first invalid field: the first element in the dialog body marked aria-invalid="true", or the first focusable element inside it. The default English text is There is 1 problem. <message> for one result and There are <count> problems. First: <message> for more. If no field is marked invalid, focus returns to the confirm button.

Pass validationAnnouncement to supply your own text, for example to localize it. It receives every validation result:

<CommandDialog<RegisterAuthor>
command={RegisterAuthor}
title="Register author"
validationAnnouncement={(results) => t('fieldsNeedAttention', { count: results.length })}>
<InputTextField value={c => c.name} title="Name" />
</CommandDialog>

onValidationFailure is still called before the announcement. A refusal without validation results keeps the generic messages.dialog.refused announcement and returns focus to the confirm button.

The response type parameter defaults to object when omitted; specify it explicitly to use response properties in onSuccess:

// Explicit response type
<CommandDialog<CreateUser, CreateUserResponse>
command={CreateUser}
title="Create User"
onSuccess={(response) => {
// response is CreateUserResponse
}}
/>
// Default object response type
<CommandDialog<CreateUser>
command={CreateUser}
title="Create User"
onSuccess={(response) => {
// response is object
}}
/>

Use onFieldValidate for immediate feedback on an edited field. It runs synchronously each time the field value changes, after the command receives the new value. Return an error message to show on that field and disable confirm, or undefined to clear that field’s custom error:

<CommandDialog<CreateUser>
command={CreateUser}
title="Create User"
onFieldValidate={(command, fieldName, oldValue, newValue) => {
if (fieldName === 'email' && !String(newValue ?? '').includes('@')) {
return 'Invalid email address';
}
return undefined;
}}
>
<InputTextField<CreateUser> value={(c) => c.email} title="Email" type="email" />
</CommandDialog>

Transform command values before execution. onBeforeExecute receives the current command values and must return the values to run with. It may be async, and it runs inside the busy state:

<CommandDialog<CreateUser>
command={CreateUser}
title="Create User"
onBeforeExecute={(values) => {
values.email = values.email.trim().toLowerCase();
return values;
}}
/>

It runs only after the user clicks confirm, so it cannot make an invalid form valid. Seed required values through initialValues, as described in Initialize command values. If the callback returns nothing, CommandDialog keeps the current values and logs a warning.

If the form values change while an async onBeforeExecute is still pending, its result is discarded: nothing is written back and the command does not run, so the newer values are never overwritten. The user confirms again to submit them.

formRef.current.execute() runs the dialog’s own submission, the one the confirm button runs. StepperCommandDialog behaves the same.

A call that submits:

  • Runs onBeforeExecute, then confirmBeforeExecute, then the command.
  • Shares the dialog’s busy state with the confirm button.
  • Invokes the result callbacks: onSuccess on success, and onFailed, onException, onUnauthorized and onValidationFailure as they apply to a failed result.
  • Closes the dialog with DialogResult.Ok on success, on the same terms as the confirm button: onConfirm or onClose can still keep it open.

Because a successful execute() already closes the dialog, do not call closeDialog yourself afterwards. The dialog has closed with DialogResult.Ok and no response value by then, so a value passed to a second closeDialog call is lost.

The promise resolves with the command result whenever the command ran, whether it succeeded or failed. It also resolves, with a result whose isSuccess is false, when the command did not run:

Situation Resolved result Callbacks
A custom field error is set (setCustomFieldError, or a message returned from onFieldValidate), including one set in the same event just before execute() or by onBeforeExecute isValid is false; validationResults holds one error per field with a message; the form’s commandResult holds it too. The same-event, transform-set and commandResult behavior needs Arc 25.7.0 or later; with older Arc, execute() refuses only the errors from the last render onFailed, then onValidationFailure, invoked but not awaited
confirmBeforeExecute did not return true isValid and isAuthorized are true, hasExceptions is false, no validation results None
The values changed while an async onBeforeExecute or the confirmation was pending Same as above None
A submission is already running, from the confirm button or from an earlier execute() that has not settled, including the result callbacks it runs for a submission Same as above None
A cancel or close is still being decided Same as above None

Always check isSuccess on the resolved result before treating the call as a completed submission.

The promise rejects only on a real error: the command, onBeforeExecute or a result callback throws. An error thrown by confirmBeforeExecute does not reject; it is reported through onException, or logged when there is none, and the call resolves as a submission that was not confirmed.

const result = await formRef.current.execute();
if (result.isSuccess) {
// The dialog has closed with DialogResult.Ok.
}

When dialog content is not built from CommandForm fields, keep the command instance synchronized with the custom input values. CommandDialog still uses command-form validity as the source of truth, and isValid is only an additional external gate.

Prefer currentValues for externally managed values so client validation sees the same command values that will be submitted. onBeforeExecute can still perform final transformations, but values populated only in onBeforeExecute are not visible to client validation before the confirm button is clicked:

<CommandDialog<UpdateProject>
command={UpdateProject}
title="Update project"
currentValues={projectDraft}
isValid={projectDraft.name.trim().length > 0}
/>

Use onFieldChange to react after an edited value has been written to the command and onFieldValidate has run:

<CommandDialog<CreateUser>
command={CreateUser}
title="Create User"
onFieldChange={(command, fieldName, oldValue, newValue) => {
console.log(`${fieldName} changed from ${oldValue} to ${newValue}`);
}}
/>

onFieldChange also receives a fifth argument, { isValid, errors }, derived from the form’s previous command result. The new value’s client validation finishes afterwards, so do not treat that argument as a fresh validation result for the edit.

When several fields need edit-time checks, branch on fieldName in one onFieldValidate callback. Each returned message blocks confirm until that field’s custom error is cleared:

const validateField = (command: CreateUser, fieldName: string, oldValue: unknown, newValue: unknown) => {
switch (fieldName) {
case 'email':
if (!newValue || !String(newValue).includes('@')) {
return 'Valid email address is required';
}
break;
case 'age':
if (Number(newValue) < 18) {
return 'Must be at least 18 years old';
}
if (Number(newValue) > 120) {
return 'Please enter a valid age';
}
break;
case 'password': {
const password = String(newValue ?? '');
if (password.length < 8) {
return 'Password must be at least 8 characters';
}
if (!/[A-Z]/.test(password)) {
return 'Password must contain an uppercase letter';
}
if (!/[0-9]/.test(password)) {
return 'Password must contain a number';
}
break;
}
}
return undefined;
};

Validate fields based on other field values. The command argument already holds the new value:

const validateField = (command: CreateUser, fieldName: string, oldValue: unknown, newValue: unknown) => {
if (fieldName === 'confirmPassword' && newValue !== command.password) {
return 'Passwords do not match';
}
if (fieldName === 'endDate' && (newValue as Date) < command.startDate) {
return 'End date must be after start date';
}
return undefined;
};

A cross-field message is attached to the field that changed. Editing password afterwards does not re-run the check for confirmPassword or clear its error, so confirm can remain disabled until the user edits confirmPassword again. Use a command validator for a rule that must be rechecked whenever either value changes.

React to one field changing, for example to update component state:

const handleFieldChange = (command: CreateOrder, fieldName: string, oldValue: unknown, newValue: unknown) => {
if (fieldName === 'country' && newValue === 'USA') {
// Could trigger state updates or side effects
console.log('Country changed to USA, update state list');
}
if (fieldName === 'quantity') {
// Calculate derived values
const total = Number(newValue) * command.pricePerUnit;
console.log('New total:', total);
}
};

To change another command property as a result, keep the value in component state and pass it through currentValues, so the form re-validates with it.

onFieldValidate is synchronous: a returned promise is not awaited. For a rule that needs the server, such as checking that a username is available, write it as a validator on the backend command and turn on server validation while the user edits:

<CommandDialog<CreateUser>
command={CreateUser}
title="Create User"
autoServerValidate
autoServerValidateThrottle={500}
>
<InputTextField<CreateUser> value={(c) => c.username} title="Username" />
</CommandDialog>

Once client validation passes, the form calls the command’s validate endpoint, waiting autoServerValidateThrottle milliseconds (500 by default) after the last change. The server result is shown on the fields and also enables or disables confirm.

Normalize values in onBeforeExecute when the command needs a different representation from the one the user entered. Return the values after changing them:

const transformBeforeExecute = (values: CreateUser): CreateUser => {
// Normalize data
values.email = values.email.toLowerCase().trim();
// Convert formats
values.dateOfBirth = new Date(values.dateOfBirth);
return values;
};

The returned values are copied onto the command by property name, and only properties the command declares are sent. Adding a key the command does not have, such as a timestamp or a derived total, has no effect; add it to the backend command if the server needs it. Do not set a required property to undefined to “remove” a UI-only field: the command’s own validation runs again before the request and rejects it.