# Blazor Forms and Validation

URL: https://flexcoreui.com/demo/forms  
Section: Components  
Controls: FormControl, FormItemControl, FormGroupControl, ValidationTooltipControl, PropertyGridControl  
Keywords: form, validation, data annotations, dynamic form, property grid, EditForm

Blazor forms from a model or laid out by hand, with data-annotation validation, field groups, templates and a property grid.

## Documentation

### Form

| Name | Type | Default | Description |
|---|---|---|---|
| Model | object? | null | The object to edit. A different instance creates a new EditContext; the form throws when both Model and EditContext are set, or neither. |
| EditContext | EditContext? | null | A context you own, for sharing validation state with code outside the form. |
| EnableDataAnnotations | bool | true | Adds the DataAnnotationsValidator, so Required, Range, MinLength, EmailAddress and the rest run for a field as its value is accepted, and for the whole model on submit. |
| ShowValidationSummary | bool | true | Shows the list of all messages above the items. |
| ShowSubmitButton | bool | true | Shows the default submit button under the items; ignored when ButtonsTemplate is set. |
| SubmitText | string | "Save" | Caption of the default submit button. |
| Columns | int | 1 | Number of columns the items flow into; one column under 600 px wide. |
| ColumnSpacing | string | "12px" | Gap between the items. |
| ChildContent | RenderFragment? | null | Your own items, groups and templates. When null, the items are generated from the model. |
| ButtonsTemplate | RenderFragment? | null | Replaces the default submit button; a ButtonControl with ButtonType="submit" still submits. |
| ValidatorTemplate | RenderFragment? | null | Extra validator components rendered inside the form, for example a custom validator alongside or instead of data annotations. |

### Form events

| Name | Type | Description |
|---|---|---|
| OnSubmit | EditContext | On every submit, before validation. |
| OnValidSubmit | EditContext | After a submit whose validation passed. |
| OnInvalidSubmit | EditContext | After a submit whose validation failed; the messages are already in the context. |
| OnUpdate | FormFieldChangedArgs | After any item has accepted a value and written it to the model. |

### Form methods

| Name | Type | Description |
|---|---|---|
| IsValid() | bool | Runs validation now and returns the result; the messages appear as if a submit had failed. |
| SubmitAsync() | Task | Submits from code: OnSubmit, then validation, then the valid or invalid event. Ignored while a submit is running or the form is disabled. |

### Item

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | Property name on the model, or a dotted path such as Address.City; every object on the path must already exist. |
| Model | object? | null | The object to edit when the item is used outside a FormControl; inside one it takes the form's model. |
| Label | string? | null | Caption. Null uses [Display(Name)], else the property name split at its capitals. |
| ShowLabel | bool | true | False hides the label; the caption still reaches the editor as its accessible name. |
| Hint | string? | null | Small text under the editor. |
| Enabled | bool | true | False shows the editor disabled. The form's Enabled, a missing public setter and [Editable(false)] have the same effect. |
| ColSpan | int | 1 | Columns the item spans in the form's grid. |
| EditorType | FormEditorType | FormEditorType.Auto | Forces an editor; see the list below for what each value does and which types it accepts. |
| Options | IEnumerable<string>? | null | Choices for the dropdown instead of the enum names or True and False. |
| ShowTime | bool | false | Shows the time part in the date picker. |
| Rows | int | 3 | Lines of a TextArea editor. |
| Culture | CultureInfo | CultureInfo.CurrentCulture | Culture used to show and parse values. |
| Template | RenderFragment<FormFieldContext>? | null | Your own editor; it receives a FormFieldContext and writes back through SetValueAsync. |
| CssClass | string? | null | Added to the item's element. |

### Item events

| Name | Type | Description |
|---|---|---|
| ValueChanged | FormFieldChangedArgs | After this item has accepted a value; the form's OnUpdate follows. |
| OnKeyDown | KeyboardEventArgs | Key presses in the built-in editors, for example to submit on Enter. |

### Item methods

| Name | Type | Description |
|---|---|---|
| FocusAsync() | Task | Focuses the item's editor. |
| SetValueAsync(object? value) | Task | Writes a typed value as if the user had entered it: validation message, ValueChanged and OnUpdate included. |

### Ctx

| Name | Type | Default | Description |
|---|---|---|---|
| Model | object | required | The object that owns the property; for a dotted path, the nested object. |
| Property | PropertyInfo | required | The property being edited. |
| Field | FieldIdentifier | required | The FieldIdentifier the context uses for messages. |
| SetValueAsync | Func<object?, Task> | required | Writes a value through the item, with its checks and events. |
| Value | object? |  | The current value, read from the property. |

### Group

| Name | Type | Default | Description |
|---|---|---|---|
| Label | string? | null | The fieldset's legend. |
| Columns | int | 1 | Columns inside the group; the group itself spans the whole form. |
| Spacing | string | "12px" | Gap between the group's items. |
| ChildContent | RenderFragment? | null | The items in the group. |

### Tooltip

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | The field whose messages the tooltip shows. |
| Model | object? | null | The owner of the field when it is not the form's model. |
| Label | string | "Validation details" | Accessible name of the focusable host. |
| ChildContent | RenderFragment? | null | What the user hovers or focuses. |

### Message

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | Property name or dotted path. |
| Model | object? | null | The owner of the field when it is not the form's model. |
| Id | string? | null | Id of the message container, for aria-describedby. |
| CssClass | string? | null | Added to each message. |

### Summary

| Name | Type | Default | Description |
|---|---|---|---|
| Model | object? | null | Limits the summary to one model's messages; null shows the whole context. |
| CssClass | string? | null | Added to the summary element. |

### Css

| Name | Description |
|---|---|
| fx-form | The form element; fx-form-items is the grid inside it, with the column count in --fx-form-columns. |
| fx-form-item | One item: label, editor, optional small hint, then the messages. |
| fx-form-group | A group's fieldset. |
| fx-validation-messages | A field's message container; each message is fx-validation-message. |
| fx-validation-summary | The summary block. |
| fx-validation-tooltip-host | The focusable wrapper; fx-validation-tooltip is the bubble, shown on hover or focus while it holds a message. |

### Grid

| Name | Type | Default | Description |
|---|---|---|---|
| Value | TModel? | null | The object to edit; its runtime type decides the rows. Nothing renders while it is null. |
| ValueChanged | EventCallback<TModel?> |  | Raised with the same object after a built-in editor has written a value to it; a text box writes on each keystroke that converts to the property type. Not raised while CustomEditor is set, so report changes from the fragment's own editors. |
| CssClass | string | "" | Added to the outer fx-propertygrid element. |
| CustomEditor | RenderFragment<(TModel? Model, System.Reflection.PropertyInfo Prop)>? | null | Draws the editor cell of every row in place of the built-in editor. It receives the model and the row's PropertyInfo as (Model, Prop); branch on Prop and render a FormItemControl with ShowLabel="false" for the rows that keep the built-in editor, as the example does. |

### Grid editors

| Name | Description |
|---|---|
| enum | DropDownListControl listing the enum's names, with a blank entry first when the property is nullable. |
| bool? | DropDownListControl with a blank entry, True and False. |
| bool | CheckBoxControl. |
| DateTime, DateOnly | DatePickerControl, also for the nullable forms; it shows the time when the property carries [DataType(DataType.DateTime)]. |
| TimeOnly | TimePickerControl, also for the nullable form. |
| any other type | TextBoxControl: string, the number types, Guid and the rest. Text is converted to the property type with the current culture; a type that does not convert from text, such as a nested object, shows its ToString() and rejects every edit. |

## Examples

### Generated

```razor
@using System.ComponentModel.DataAnnotations
@using Fx.ControlKit

<div class="fm">
    <FormControl Model="@_leave" Columns="2" OnValidSubmit="LeaveSaved" OnInvalidSubmit="LeaveInvalid" />
    <p class="result">@_leaveStatus</p>
</div>
```

```csharp
private LeaveRequest _leave = new();

private string _leaveStatus = "Not saved yet.";

private void LeaveSaved() => _leaveStatus = $"{_leave.Reference} saved: {_leave.Name}, {_leave.LeaveType} leave, days requested: {_leave.Days}, starting {_leave.Starts:g}.";

private void LeaveInvalid() => _leaveStatus = "Correct the fields with a message.";

public enum LeaveType { Vacation, Sick, Parental }

public sealed class LeaveRequest
{
    [Display(AutoGenerateField = false)] public Guid Id { get; set; } = Guid.NewGuid();
    [Required, MinLength(2), Display(Name = "Employee", Order = 0)] public string Name { get; set; } = "Albus Door";
    [Range(1, 20), Display(Order = 1)] public int Days { get; set; } = 5;
    [Display(Order = 2)] public LeaveType LeaveType { get; set; } = LeaveType.Vacation;
    [Display(Name = "Starts on", Order = 3), DataType(DataType.DateTime)] public DateTime Starts { get; set; } = new(2026, 11, 23, 9, 0, 0);
    [Display(Order = 4)] public TimeOnly Handover { get; set; } = new(16, 0);
    [Display(Name = "Manager approval", Order = 5)] public bool? Approved { get; set; }
    [Display(Order = 6)] public bool CoverArranged { get; set; } = true;
    [Editable(false), Display(Order = 7)] public string Reference { get; set; } = "LR-0118";
    [Display(Order = 8)] public string Notes { get; set; } = "";
}
```

### Handbuilt

```razor
@using System.ComponentModel.DataAnnotations
@using Fx.ControlKit

<div class="fm">
    <FormControl @ref="_form" Model="@_opening" Columns="2" ShowValidationSummary="false"
                 OnValidSubmit="OpeningSent" OnInvalidSubmit="OpeningInvalid" OnUpdate='a => _last = $"{a.Field} = {a.Value}"'>
        <ChildContent>
            <FormGroupControl Label="Contact" Columns="2">
                <FormItemControl Field="Name" />
                <FormItemControl Field="Email" />
                <FormItemControl Field="Address.City" Label="City" />
                <ValidationTooltipControl Field="Name" Label="Name rules"><span class="rules">Name rules</span></ValidationTooltipControl>
            </FormGroupControl>
            <FormItemControl Field="JobTitle" />
            <FormItemControl Field="Openings" Hint="A template replaces the editor; the field context sets the value.">
                <Template Context="field">
                    <div class="stepper">
                        <ButtonControl CssClass="btn-sm" OnClick="() => field.SetValueAsync((int)field.Value! - 1)">−</ButtonControl>
                        <strong>@field.Value</strong>
                        <ButtonControl CssClass="btn-sm" OnClick="() => field.SetValueAsync((int)field.Value! + 1)">+</ButtonControl>
                    </div>
                </Template>
            </FormItemControl>
            <FormItemControl Field="Notes" EditorType="FormEditorType.TextArea" Rows="4" />
        </ChildContent>
        <ButtonsTemplate>
            <ButtonControl ButtonType="submit">Send</ButtonControl>
            <ButtonControl OnClick='() => _openingStatus = _form!.IsValid() ? "Valid." : "Not valid yet."'>Check</ButtonControl>
        </ButtonsTemplate>
    </FormControl>
    <p class="result">@_openingStatus Last change: @_last</p>
</div>
```

```csharp
private FormControl? _form;

private OpeningRequest _opening = new();

private string _openingStatus = "Not sent.", _last = "none.";

private void OpeningSent()
{
    var city = string.IsNullOrWhiteSpace(_opening.Address.City) ? "" : $" in {_opening.Address.City}";
    _openingStatus = $"Request sent by {_opening.Name}{city}: {_opening.Openings} × {_opening.JobTitle}.";
}

private void OpeningInvalid() => _openingStatus = "Not sent: correct the fields.";

public sealed class OpeningRequest
{
    [Required, MinLength(2)] public string Name { get; set; } = "";
    [Required, EmailAddress] public string Email { get; set; } = "";
    public Address Address { get; set; } = new();
    [Required, Display(Name = "Job title")] public string JobTitle { get; set; } = "Reservations agent";
    [Range(1, 20)] public int Openings { get; set; } = 1;
    public string Notes { get; set; } = "";
}

public sealed class Address
{
    public string City { get; set; } = "";   // the data-annotation validator checks the top-level model only, so no attribute here
}
```

### Property grid

```razor
@using System.ComponentModel.DataAnnotations
@using Fx.ControlKit

<ToggleButtonControl @bind-Selected="_levelButtons">Level as buttons</ToggleButtonControl>
<div class="record-grid">
    @if (!_levelButtons)
    {
        <PropertyGridControl TModel="EmployeeRecord" Value="@_employee" ValueChanged="EmployeeChanged" />
    }
    else
    {
        <PropertyGridControl TModel="EmployeeRecord" Value="@_employee">
            <CustomEditor Context="row">
                @if (row.Prop.Name == nameof(EmployeeRecord.Level))
                {
                    <ButtonGroupControl Items="@Levels" Values="@(new[] { _employee.Level.ToString() })" ValuesChanged="LevelChanged" AriaLabel="Level" />
                }
                else
                {
                    <FormItemControl Model="@row.Model" Field="@row.Prop.Name" ShowLabel="false" ValueChanged="EmployeeChanged" />
                }
            </CustomEditor>
        </PropertyGridControl>
    }
</div>
<p class="result">@_employee.Summary Changes reported: @_changes.</p>
```

```csharp
private EmployeeRecord _employee = new();
private int _changes;
private bool _levelButtons;
private static readonly SelectionItem[] Levels = Enum.GetNames<Level>().Select(s => new SelectionItem(s, s)).ToArray();
private void EmployeeChanged() => _changes++;
private void LevelChanged(IReadOnlyList<string> values)
{
    var level = Enum.Parse<Level>(values[0]);
    if (level == _employee.Level) return;   // clicking the selected level changes nothing
    _employee.Level = level;
    _changes++;
}

public enum Level { Junior, Mid, Senior, Lead }

public sealed class EmployeeRecord
{
    [Editable(false)] public string EmployeeId { get; set; } = "EMP-0042";
    public string Name { get; set; } = "Luna Goodlove";
    public string Office { get; set; } = "Kyoto";
    public int VacationDays { get; set; } = 20;
    public decimal TrainingBudget { get; set; } = 1200.00m;
    public Level Level { get; set; } = Level.Senior;
    public bool FullTime { get; set; } = true;
    public DateTime StartDate { get; set; } = new(2024, 3, 4);
    // No setter, so the grid gives it no row.
    public string Summary => $"{EmployeeId}: {Name}, {Office}, {Level}, {VacationDays} vacation days, started {StartDate:MMM d, yyyy}, training budget {TrainingBudget:0.00}, {(FullTime ? "full time" : "part time")}.";
}
```

