Covers Blazor EditForm and EditContext, DataAnnotationsValidator, input components, custom validation attributes, .NET 10 nested validation, mapping ProblemDetails errors with ValidationMessageStore, and SSR forms with FormName, SupplyParameterFromForm and antiforgery.
EditForm wraps a model in an EditContext, which tracks which fields changed and holds validation messages. Add <DataAnnotationsValidator />, the built-in inputs (InputText, InputNumber, InputDate, InputSelect) and <ValidationMessage For="..." />, and handle OnValidSubmit. Custom rules are a ValidationAttribute or IValidatableObject. In .NET 10, AddValidation() with [ValidatableType] also validates nested objects and collections.
When the API rejects the request, read its ProblemDetails errors and put them into a ValidationMessageStore so they appear next to the fields. A form rendered with static SSR needs a FormName and [SupplyParameterFromForm], and antiforgery is checked by UseAntiforgery. The trade-off: client validation gives fast feedback, but only the server's validation counts.
"In Blazor the form is an
EditFormbound to a model. It creates anEditContext, which tracks which fields the user touched and holds the validation messages for each field. I addDataAnnotationsValidator, use the built-in input components so they raise change notifications and getvalid/invalidCSS classes, and put aValidationMessageunder each input.OnValidSubmitonly runs when the model passes validation.For single-field rules beyond
[Required]and[Range], I write aValidationAttribute. For rules that compare fields, such as an end date after a start date, I implementIValidatableObjecton the model and return aValidationResultthat names the members, so the message appears under the right input. I put the request model in a shared project so the same rules run in the browser and in the API. New in .NET 10, if I callbuilder.Services.AddValidation()and mark the model with[ValidatableType], the validator also walks nested objects and collections, such as the address on a customer or the lines on an order. Before .NET 10 that needed a third-party validator.The API always validates again, because client validation is just UX. When it returns a 400 with ProblemDetails, I read the
errorsdictionary and add each message to aValidationMessageStorekeyed by field, then callNotifyValidationStateChanged, so the server's message appears under the right input. If the page uses static SSR, the form posts back like an MVC form: it needs a uniqueFormName, the model gets[SupplyParameterFromForm], and the antiforgery token thatEditFormrenders is checked byapp.UseAntiforgery(). The mistake I see is trusting the Blazor validation and skipping it on the API: anyone can post straight to the endpoint."
| Piece | Job |
|---|---|
EditForm |
Creates/owns the EditContext, renders <form>, raises submit events |
EditContext |
Field state, validation messages, Validate() |
DataAnnotationsValidator |
Runs DataAnnotations rules, per field on change and all on submit |
InputText, InputNumber, InputDate, InputSelect, InputCheckbox |
Bind values, notify field changes, add validation CSS classes |
ValidationMessage For / ValidationSummary |
Show messages |
ValidationMessageStore |
Add your own messages, e.g. from the server |
| Rule | Mechanism | Runs in browser | Runs on server |
|---|---|---|---|
| Required, length, pattern | Attribute on shared model | Yes | Yes |
| Cross-field (dates, totals) | IValidatableObject |
Yes | Yes |
| Needs data (unique ABN, stock) | API check → ProblemDetails | No | Yes |
| Business invariant | Domain model / handler | No | Yes |
| Event | Runs when |
|---|---|
OnValidSubmit |
Validation passes |
OnInvalidSubmit |
Validation fails |
OnSubmit |
Always; you call editContext.Validate() yourself |
| Interactive (Server/WASM) | Static SSR | |
|---|---|---|
| Validation on field change | Yes | No; on post |
| Model binding | Two-way binding in memory | Form post bound with [SupplyParameterFromForm] |
| Name | Optional | FormName required and unique on the page |
| Antiforgery | Token rendered, checked by middleware | Same, and essential |
| Enhanced post (no full reload) | n/a | Enhance parameter on EditForm |
On a supplier onboarding form with [40] fields, we shared the request records between the Blazor client and the API and mapped ProblemDetails errors into the form. Duplicate-ABN errors, which only the server can detect, started showing under the ABN field instead of a generic toast, and abandoned submissions dropped by about [25%].
Checks that the candidate can build a real Blazor form end to end: client validation for UX, server validation for truth, and field-level server errors.
Green flags
EditForm, DataAnnotationsValidator and the Input* components correctlyValidationMessageStoreFormName, [SupplyParameterFromForm] and antiforgeryRed flags
InputText (Value, ValueChanged, ValueExpression)
-> user types -> ValueChanged -> model property set
-> EditContext.NotifyFieldChanged(FieldIdentifier)
-> OnFieldChanged event -> DataAnnotationsValidator validates that field
-> ValidationMessageStore updated -> OnValidationStateChanged
-> ValidationMessage components re-render
A FieldIdentifier is (model object, property name). That is why For="() => model.Email" takes an expression: Blazor extracts the object and property from it to find the right messages.
Each validator owns a ValidationMessageStore. The EditContext reports the union of all stores. Server errors go in your own store, which you clear when the user edits that field, otherwise a stale "email already used" message sticks after they fix it.
DataAnnotations on its own validates only the top-level object's properties. .NET 10 adds a source-generated validation system (the same one Minimal APIs use). You call AddValidation() and mark a top-level type with [ValidatableType]; the generator discovers nested types and collection items, and DataAnnotationsValidator uses it. At the time of writing, the attribute lives in an experimental namespace, so the compiler emits an experimental warning you suppress deliberately.
ASP.NET Core's ValidationProblemDetails returns errors as { "Email": ["..."], "Lines[0].Quantity": ["..."] }. Top-level keys map directly to new FieldIdentifier(model, key). Nested keys need you to resolve the path to the nested object; many teams map top-level keys to fields and show the rest in the summary.
If the API serialises with camelCase dictionary keys, email will not match the C# property Email; compare case-insensitively.
Without a circuit, the browser posts the form. The framework finds the handler by FormName (the _handler field), binds form fields into the [SupplyParameterFromForm] property, runs the component again and executes OnValidSubmit on the server. EditForm renders an <AntiforgeryToken />, and UseAntiforgery() (after authentication and authorisation) rejects posts without a valid token. Phase 14 covers CSRF itself.
invalid CSS class appear on blur.AddValidation(), see nested errors ignored, then turn it on.FormName from a static SSR form and read the error.curl without the antiforgery token and confirm the 400.A shared request model, the API endpoint, and the Blazor form that shows both client and server errors.
// Shared/CreateCustomer.cs (referenced by the API and the Blazor client)
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Validation;
namespace Shop.Shared;
#pragma warning disable ASP0029 // ValidatableType is experimental in .NET 10
[ValidatableType]
#pragma warning restore ASP0029
public sealed class CreateCustomer
{
[Required, StringLength(100)] public string Name { get; set; } = "";
[Required, EmailAddress] public string Email { get; set; } = "";
[Required, Abn] public string Abn { get; set; } = "";
public Address Address { get; set; } = new(); // nested: validated in .NET 10
}
public sealed class Address
{
[Required] public string Street { get; set; } = "";
[Required, RegularExpression(@"^\d{4}$", ErrorMessage = "Postcode must be 4 digits.")]
public string Postcode { get; set; } = "";
}
// Custom rule: 11 digits (checksum omitted for brevity)
public sealed class AbnAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext ctx) =>
value is string s && s.Replace(" ", "").Length == 11 && s.Replace(" ", "").All(char.IsDigit)
? ValidationResult.Success
: new ValidationResult("Enter an 11-digit ABN.", [ctx.MemberName!]);
}
// API Program.cs: validates again and returns ValidationProblemDetails
builder.Services.AddValidation(); // .NET 10 Minimal API validation
app.MapPost("/api/customers", async (CreateCustomer req, ICustomerStore store, CancellationToken ct) =>
{
if (await store.AbnExistsAsync(req.Abn, ct))
return Results.ValidationProblem(new Dictionary<string, string[]>
{
[nameof(CreateCustomer.Abn)] = ["A customer with this ABN already exists."]
});
var id = await store.AddAsync(req, ct);
return Results.Created($"/api/customers/{id}", new { id });
});
@* NewCustomer.razor (interactive) *@
@page "/customers/new"
@rendermode InteractiveServer
@inject HttpClient Http
@inject NavigationManager Nav
<EditForm EditContext="editContext" OnValidSubmit="SubmitAsync">
<DataAnnotationsValidator />
<ValidationSummary />
<label>Name <InputText @bind-Value="model.Name" /></label>
<ValidationMessage For="() => model.Name" />
<label>Email <InputText @bind-Value="model.Email" type="email" /></label>
<ValidationMessage For="() => model.Email" />
<label>ABN <InputText @bind-Value="model.Abn" /></label>
<ValidationMessage For="() => model.Abn" />
<label>Postcode <InputText @bind-Value="model.Address.Postcode" /></label>
<ValidationMessage For="() => model.Address.Postcode" />
<button type="submit" disabled="@saving">Save</button>
</EditForm>
@code {
private readonly CreateCustomer model = new();
private EditContext editContext = default!;
private ValidationMessageStore serverErrors = default!;
private bool saving;
protected override void OnInitialized()
{
editContext = new EditContext(model);
serverErrors = new ValidationMessageStore(editContext);
// Clear a server message as soon as the user edits that field
editContext.OnFieldChanged += (_, e) => serverErrors.Clear(e.FieldIdentifier);
}
private async Task SubmitAsync()
{
saving = true;
serverErrors.Clear();
try
{
var response = await Http.PostAsJsonAsync("api/customers", model);
if (response.IsSuccessStatusCode) { Nav.NavigateTo("/customers"); return; }
var problem = await response.Content.ReadFromJsonAsync<HttpValidationProblemDetails>();
foreach (var (key, messages) in problem?.Errors ?? new Dictionary<string, string[]>())
{
// Keys may be camelCase; match properties case-insensitively
var prop = typeof(CreateCustomer).GetProperties()
.FirstOrDefault(p => p.Name.Equals(key, StringComparison.OrdinalIgnoreCase));
var field = prop is null ? new FieldIdentifier(model, string.Empty) : new FieldIdentifier(model, prop.Name);
serverErrors.Add(field, messages);
}
editContext.NotifyValidationStateChanged();
}
finally { saving = false; }
}
}
<input @bind> instead of InputText. Why it is wrong: plain inputs do not notify the EditContext, so per-field validation and CSS classes do not work. Instead: use the Input* components or call NotifyFieldChanged.errors into a ValidationMessageStore.OnFieldChanged.AddValidation() with [ValidatableType].IValidatableObject.Validate and return a ValidationResult naming the affected members.FormName or with [Parameter] instead of [SupplyParameterFromForm]. Why it is wrong: the post cannot be routed or bound. Instead: give each form a unique FormName and use [SupplyParameterFromForm].Validator.TryValidateObject, test the endpoint's 400 response with WebApplicationFactory, and test the form with bUnit.The senior decision is where each rule lives. Format rules (required, length, pattern) go on a shared request model so the browser and API agree. Rules needing data (duplicate ABN, credit limit) live only on the server and come back as ProblemDetails mapped to fields. Business invariants belong in the domain, not in attributes.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| DataAnnotations on a shared model | Most LOB forms | Limited to attribute-style rules | Complex cross-field logic |
IValidatableObject |
Cross-field rules on one model | Runs only after attributes pass | Rules needing a database |
| FluentValidation with a Blazor adapter | Large rule sets, team already uses it | Extra library, adapter to maintain | Simple forms (.NET 10 covers nesting now) |
| Server-only checks mapped to fields | Uniqueness, permissions, stock | One round trip | Format checks the client can do |
I measure form quality by submit failure rate and field-level error counts in Application Insights custom events.
I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.
On the server, a Minimal API with .NET 10's built-in validation (AddValidation() plus DataAnnotations on the request record) returns 400 ValidationProblemDetails automatically and 201 Created with the new DTO on success.
On the client, a small typed API module wraps fetch: it checks res.ok, parses ProblemDetails into a typed ApiError with the errors dictionary, and returns typed DTOs. The React screen uses TanStack Query: useQuery for the list and useMutation for the create, then invalidates the list so it refetches.
The form shows field errors from the server next to each input, a general message for non-field problems, and disables submit while saving. Client checks are only for speed of feedback; the trade-off is a little duplication for a much better UX, with the server as the source of truth.
Disabling the button only stops the common case; retries, two tabs or a flaky network can still send the request twice. Make the write idempotent: the client generates an idempotency key (a GUID) when the form is opened or first submitted and reuses the same key on every retry of that submission, sending it in an Idempotency-Key header. The API inserts the key and the result in the same database transaction as the create, protected by a unique constraint, and returns the stored response for repeats (a concurrent duplicate that loses the race gets 409 or waits and replays). A natural unique key such as the SKU adds a second guard. Keys carry a TTL (for example 24 hours) and a scheduled job deletes expired rows. For UX, the client treats a replayed response as success and shows the saved record, so the user never sees 'already exists'.
Last updated 23 Nov 2026.