FormErrorsAndGuard
Lists the errors of a form and announces them (KlyFormErrorSummary), and blocks navigation while a form has unsaved changes (KlyFormNavigationGuard). Both take a controller, typed or dynamic.
On this page
Examples
Error summary in your own layout
KlyFormEngine and KlyFormPage already draw a summary, so the component is for a layout of your own. After a failed submit it lists each field error as a button that moves focus to the field and a polite live region announces the count and the first error. SetFormError reports a failure that belongs to no field, and it is listed at once.
@implements IDisposable
@* A layout of your own: the form components draw their own summary, so one is added here by hand. It lists the field errors after a failed submit and the form-level errors at once. *@
<CascadingValue Value="_form">
<div class="flex w-full max-w-lg flex-col gap-4">
<KlyFormErrorSummary Form="_form" />
<KlyFormFieldView Field="_email" />
<KlyFormFieldView Field="_code" />
<div class="flex items-center gap-3">
<KlyButton Label="Redeem" OnClick="RedeemAsync" />
<span class="text-sm text-(--klyroo-text-muted)">@_status</span>
</div>
</div>
</CascadingValue>
@code {
private static readonly FormSchema<Voucher> Schema = FormSchema.For<Voucher>(s =>
{
s.FormKey = "voucher";
s.Field(m => m.Email, f => f.Label("Email").Required().Rule(v => v.Contains('@'), "Enter a valid email address"));
s.Field(m => m.Code, f => f.Label("Voucher code").Required());
});
private readonly FormController<Voucher> _form = new(Schema);
private readonly FormField<Voucher, string> _email = Schema.Field(m => m.Email);
private readonly FormField<Voucher, string> _code = Schema.Field(m => m.Code);
private string _status = "";
protected override void OnInitialized() => _form.Changed += OnChanged;
private void OnChanged() => InvokeAsync(StateHasChanged);
// Valid fields are not enough: a save that fails for a reason that belongs to no field reports it with SetFormError and returns false.
private async Task RedeemAsync() => _status = await _form.SubmitAsync(SaveAsync) ? "Redeemed" : "";
private Task<bool> SaveAsync(Voucher voucher, CancellationToken cancellationToken)
{
_form.SetFormError("The voucher service is not available. Try again later.");
return Task.FromResult(false);
}
public void Dispose() => _form.Changed -= OnChanged;
public sealed class Voucher
{
public string Email { get; set; } = "";
public string Code { get; set; } = "";
}
}Navigation guard
While the form is dirty the guard asks the browser to confirm leaving the site or closing the tab, and asks window.confirm before navigating inside the app. A successful OnSave retakes the baseline, so the guard stops asking. It subscribes to the controller itself, which a NavigationLock placed on the page cannot do when the form is drawn by a component.
Edit the title, then follow this link: the guard asks before leaving, and stops asking once the form is saved.
<div class="flex w-full max-w-lg flex-col gap-4">
<KlyFormNavigationGuard Form="_form" />
<KlyFormEngine TModel="Note" Form="_form" Model="_note" SubmitLabel="Save" OnSave="SaveAsync" />
<p class="m-0 text-sm text-(--klyroo-text-muted)">
Edit the title, then follow <a href="/docs" class="underline">this link</a>: the guard asks before leaving, and stops asking once the form is saved.
</p>
</div>
@code {
private readonly Note _note = new() { Title = "Meeting notes" };
private FormController<Note> _form = default!;
private static readonly FormSchema<Note> Schema = FormSchema.For<Note>(s =>
{
s.FormKey = "note";
s.Field(m => m.Title, f => f.Required());
s.Field(m => m.Body, f => f.AsTextarea());
});
protected override void OnInitialized() => _form = new FormController<Note>(Schema, _note);
// Returning true retakes the baseline: the form is clean again and the guard lets the page go.
private Task<bool> SaveAsync(Note note, CancellationToken cancellationToken) => Task.FromResult(true);
public sealed class Note
{
public string Title { get; set; } = "";
public string Body { get; set; } = "";
}
}Your own confirmation
ConfirmLeave receives the navigation: return true to let it go ahead and false to stay, for example after asking in a KlyModal. Message changes the question of the default confirmation, ConfirmExternalNavigation turns off the browser prompt and Disabled turns off the guard.
Edit the title, then follow this link: a dialog of your own answers instead of the browser prompt.
<KlyFormNavigationGuard Form="_form" ConfirmLeave="AskAsync" ConfirmExternalNavigation="false" />
<div class="flex w-full max-w-lg flex-col gap-4">
<KlyFormEngine TModel="Note" Form="_form" Model="_note" SubmitLabel="Save" ShowReset="false" />
<p class="m-0 text-sm text-(--klyroo-text-muted)">
Edit the title, then follow <a href="/docs" class="underline">this link</a>: a dialog of your own answers instead of the browser prompt.
</p>
</div>
<KlyModal Open="_asking" OpenChanged="Answered" Title="Leave this page?" Description="You have unsaved changes." Close="false" Size="KlySize.Sm">
<Footer>
<KlyButton Label="Stay" Color="KlyColor.Neutral" Variant="ButtonVariant.Outline" OnClick="@(() => Answer(false))" />
<KlyButton Label="Leave" Color="KlyColor.Error" OnClick="@(() => Answer(true))" />
</Footer>
</KlyModal>
@code {
private readonly Note _note = new() { Title = "Meeting notes" };
private FormController<Note> _form = default!;
private TaskCompletionSource<bool>? _answer;
private bool _asking;
private static readonly FormSchema<Note> Schema = FormSchema.For<Note>(s =>
{
s.FormKey = "note";
s.Field(m => m.Title, f => f.Required());
});
protected override void OnInitialized() => _form = new FormController<Note>(Schema, _note);
// Return true to let the navigation go ahead, false to stay.
private Task<bool> AskAsync(LocationChangingContext context)
{
_answer = new TaskCompletionSource<bool>();
_asking = true;
InvokeAsync(StateHasChanged);
return _answer.Task;
}
private void Answer(bool leave)
{
_asking = false;
_answer?.TrySetResult(leave);
}
// Escape and a click on the backdrop close the dialog: that is a "stay".
private void Answered(bool open)
{
_asking = open;
if (!open) _answer?.TrySetResult(false);
}
public sealed class Note
{
public string Title { get; set; } = "";
}
}API
KlyFormErrorSummary
Parameters
| Name | Type | Description |
|---|---|---|
Class |
string |
Classes added to the root element, merged last so they win over the theme. |
Form (required) |
IFormRuntime |
The controller whose errors to list: a FormController`1 or a DynamicFormController . |
KlyFormNavigationGuard
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
Class |
string |
Classes added to the root element, merged last so they win over the theme. | |
Confirm |
bool |
true |
Asks the browser to confirm leaving the site, reloading or closing the tab while the form is dirty. The browser shows its own text; it cannot be changed. The default is true . |
ConfirmLeave |
Func |
Called when the user navigates inside the app while the form is dirty. Return true to let the navigation go ahead and false to stay, for example after asking in a KlyModal . Without it the guard asks with window.confirm and Message . | |
Disabled |
bool |
false |
Turns the guard off, for example while the page saves and navigates on its own. The default is false . |
Form (required) |
IFormRuntime |
The controller to protect: a FormController`1 or a DynamicFormController . Navigation is blocked while IsDirty is true , so the guard stops once a submission succeeds and the snapshot is retaken. | |
Message |
string |
The question of the default confirmation. The default is the UnsavedChanges text of the current locale ( UnsavedChanges ). |