Skip to main content

LgEditForm

LgEditForm wraps Lagoon input fields: it constructs the EditContext for the model, triggers validation, and exposes submission events. All Lg* fields placed inside automatically participate in validation; the DataAnnotations validator and validation summary (LgValidationSummary) are added automatically.

<LgEditForm Model="_model" OnValidSubmit="OnValidSubmitAsync">
...
</LgEditForm>
  • Namespace: Lagoon.UI.Components
  • Inherits from: LgComponentBase
  • NuGet package: Lagoon.UI

Usage​

Simple form​

Model designates the model being edited (an EditContext is constructed for it) and OnValidSubmit is triggered on submission when the model is valid.

ContactEditPage.razor
<LgEditForm Model="_contact" OnValidSubmit="SaveAsync">
<LgTextBox Label="#Name" @bind-Value="_contact.Name" />
<LgTextBox Label="#Email" @bind-Value="_contact.Mail" />
<LgButton Text="#Save" IsSubmit="true" />
</LgEditForm>
ContactEditPage.razor.cs
public partial class ContactEditPage : LgPage
{
// Model edited by the form: carries the validation DataAnnotations.
private readonly ContactVm _contact = new();

// Triggered only when the model is valid: this is where to persist.
private async Task SaveAsync(EditContext editContext)
{
try
{
await Http.TryPostAsync("api/contacts", _contact);
}
catch (Exception ex)
{
ShowException(ex);
}
}

private sealed class ContactVm
{
[Required]
[MaxLength(50)]
public string Name { get; set; }

[EmailAddress]
public string Mail { get; set; }
}
}

The three levels of validation​

  • DataAnnotations: attributes placed on model properties ([Required], [MaxLength(50)], [EmailAddress], …). Validated on the client (on field exit) and on the server.
  • IValidatableObject: multi-property rules implemented on the model, evaluated on submission on the client and on receipt of the view model on the server.
  • ModelState: validations that can only be performed on the server, in the controller action.
Always validate on the server

Client-side validation avoids round-trips, but it is easily bypassed. For server validation to be automatic, the controller must inherit from LgControllerBase (or have [ApiController]).

For models with nested properties carrying DataAnnotations, enable UseValidationComplexModel="true" (the form then uses an ObjectGraphDataAnnotationsValidator). To add business errors programmatically, use LgValidator.

Invalid submission and raw submission​

OnInvalidSubmit is triggered when the model is invalid. OnSubmit bypasses automatic validation: you are then responsible for calling EditContext.Validate(). Do not combine OnSubmit with OnValidSubmit / OnInvalidSubmit.

AuditFormPage.razor
<LgEditForm Model="_model"
OnValidSubmit="OnValidSubmitAsync"
OnInvalidSubmit="OnInvalidSubmit">
<LgTextBox Label="#Reference" @bind-Value="_model.Reference" />
<LgButton Text="#Save" IsSubmit="true" />
</LgEditForm>
AuditFormPage.razor.cs
public partial class AuditFormPage : LgPage
{
private readonly AuditVm _model = new();

// Persists the valid model.
private async Task OnValidSubmitAsync(EditContext editContext)
{
await Task.Delay(100);
ShowSuccess("#Saved");
}

// Traces invalid submission attempts (audit, telemetry, …).
private void OnInvalidSubmit(EditContext editContext)
{
ShowWarning("#FormInvalid");
}

private sealed class AuditVm
{
[Required]
public string Reference { get; set; }
}
}

Error display and required fields​

ErrorsDisplayOptions chooses how errors are presented (message below the field, summary, toastr, …); by default, the application's behavior configuration applies. ValidationErrorMessage replaces the generic toastr message. RequiredInputDisplayMode controls the marking of required / optional fields.

OrderFormPage.razor
<LgEditForm Model="_model"
ErrorsDisplayOptions="EditFormErrorsDisplayOptions.InlineValidation | EditFormErrorsDisplayOptions.Summary"
RequiredInputDisplayMode="RequiredInputDisplayMode.MandatoryOnly"
ValidationErrorMessage="#OrderFormInvalid"
OnValidSubmit="OnValidSubmitAsync">
...
</LgEditForm>

Confirmation, Enter key, and change tracking​

ConfirmationMessage requests confirmation before submission (this is where it is placed when the button is in IsSubmit="true"). SubmitOnEnter (enabled by default) submits the form on the Enter key. IgnoreFormTracking excludes the form from change tracking (LgFormTracker), which otherwise alerts the user if closing with unsaved changes.

SettingsFormPage.razor
<LgEditForm Model="_model"
ConfirmationMessage="#ConfirmSaveSettings"
SubmitOnEnter="false"
IgnoreFormTracking="true"
OnValidSubmit="OnValidSubmitAsync">
...
</LgEditForm>

Properties​

All [Parameter] properties of the component.

NameTypeDefaultDeclared inDescription
AdditionalAttributesIReadOnlyDictionary<string, object>nullLgEditFormAdditional HTML attributes applied to the form element.
ChildContentRenderFragment<EditContext>nullLgEditFormForm content (the EditContext is available in context).
ConfirmationMessagestringnullLgEditFormConfirmation message displayed before submission.
CssClassstringnullLgEditFormAdditional CSS classes.
EditContextEditContextnullLgEditFormEdit context provided explicitly. Exclusive with Model.
ErrorsDisplayOptionsEditFormErrorsDisplayOptions?nullLgEditFormValidation error display mode. If null, the application's configuration applies.
IgnoreFormTrackingboolfalseLgEditFormExcludes the form from change tracking.
ModelobjectnullLgEditFormTop-level form model (an EditContext is constructed for it). Exclusive with EditContext.
OnInvalidSubmitEventCallback<EditContext>—LgEditFormCallback triggered on submission when the model is invalid.
OnSubmitEventCallback<EditContext>—LgEditFormRaw submission: validation is then your responsibility (EditContext.Validate()).
OnValidSubmitEventCallback<EditContext>—LgEditFormCallback triggered on submission when the model is valid.
RequiredInputDisplayModeRequiredInputDisplayMode?nullLgEditFormRequired / optional field marking mode. If null, the application's configuration applies.
SubmitOnEnterbooltrueLgEditFormSubmits the form on the Enter key.
UseValidationComplexModelbool?nullLgEditFormEnables validation of nested properties (ObjectGraphDataAnnotationsValidator).
ValidationErrorMessagestringnullLgEditFormReplaces the generic toastr error message (#lgEditFormValidation).
Cascading parameters

LgEditForm consumes the FormTracker (LgFormTracker) provided by an ancestor for change tracking — you do not need to define it.

Events​

EventTypeDescription
OnValidSubmitEventCallback<EditContext>On submission, when the model is valid.
OnInvalidSubmitEventCallback<EditContext>On submission, when the model is invalid.
OnSubmitEventCallback<EditContext>On submission, without automatic validation.

Associated enumerations​

EditFormErrorsDisplayOptions​

Validation error display mode (property ErrorsDisplayOptions). [Flags] enumeration: values combine (e.g. InlineValidation | Summary).

ValueDescription
NoneNo message displayed.
ToastrGenericMessageGeneric message in the toastr (default option).
ToastrAllMessagesAll validation messages in the toastr.
ToastrOnBlurMessage in the toastr on field exit.
SummarySummary of messages at the top of the form.
InlineValidationMessage below each field (default option).

RequiredInputDisplayMode​

Marking of required / optional fields (property RequiredInputDisplayMode).

ValueDescription
NoneNo indication.
OptionalOnlyIndication on optional fields.
MandatoryOnlyIndication on required fields.
BothIndication on both.

Best practices / accessibility​

  • Place constraints on the view model (DataAnnotations): they carry client and server validation, as well as field inferences (Required, MaxLength).
  • One submission mode only: OnValidSubmit / OnInvalidSubmit or OnSubmit, not both.
  • Form ConfirmationMessage is incompatible with that of a button with IsSubmit="true": place the confirmation on the form.
Complete reference

Input fields in this section: LgTextBox, LgSelect, LgCheckBox, LgCheckBoxList, LgRadioGroup, LgDateBox, LgMonthBox, LgWeekBox.

To add custom validation errors (business rules, server errors) to the form: LgValidator.