skip to content

In a Blazor Web App, how do EditForm, DataAnnotationsValidator, ValidationMessage and ValidationSummary work together to validate a form?

level: juniorimportance: must knowfreq 72%

answer

  1. EditForm cascades an EditContext
  2. no validator component, no attribute checks
  3. field check on change, full check on submit
  4. ValidationMessage For="() => Model.Email"
  5. .NET 10: AddValidation for nested objects

basics

~20 s

EditForm builds an EditContext for its Model and cascades it. DataAnnotationsValidator subscribes to it and runs the model's attributes on each field change and on submit; ValidationMessage shows one field's errors and ValidationSummary lists them all.

solid answer

~40 s

`<EditForm Model="Volunteer">` creates an `EditContext` and cascades it to everything inside. `DataAnnotationsValidator` is what connects the model's attributes to that context: without it, `[Required]` and friends are simply ignored. It validates one property when an input reports a change and the whole model when `EditForm` calls `EditContext.Validate()` on submit, which then routes to `OnValidSubmit` or `OnInvalidSubmit`. `<ValidationMessage For="() => Volunteer.Email" />` renders that field's messages, and `<ValidationSummary />` renders every message, including model-level ones that name no member. Input components add `valid`/`invalid` CSS classes and `aria-invalid`. In ASP.NET Core 10 nested objects and collections are validated only after `AddValidation()` with a `[ValidatableType]` root model; otherwise only top-level properties are checked.

code

razor · 16 lines
razor
<EditForm Model="Volunteer" FormName="volunteer-signup"
          OnValidSubmit="RegisterAsync" OnInvalidSubmit="LogInvalid">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <label>Full name <InputText @bind-Value="Volunteer.FullName" /></label>
    <ValidationMessage For="() => Volunteer.FullName" />

    <label>Email <InputText @bind-Value="Volunteer.Email" /></label>
    <ValidationMessage For="() => Volunteer.Email" />

    <label>Hours per week <InputNumber @bind-Value="Volunteer.HoursPerWeek" /></label>
    <ValidationMessage For="() => Volunteer.HoursPerWeek" />

    <button type="submit">Register</button>
</EditForm>

go deeper

for a junior

Recall the four pieces: EditForm with a Model, DataAnnotationsValidator inside it, ValidationMessage per field and ValidationSummary for all messages.

for a middle

Explain the EditContext as the hub: field-change validation versus Validate() on submit, and why model-level messages appear only in a summary.

for a senior

Show where static SSR differs, why nested rules are skipped by default, and how AddValidation with [ValidatableType] changes that in ASP.NET Core 10.

for a principal

Weigh keeping DataAnnotations rules on shared form models against dedicated form DTOs, and whether to adopt the experimental ASP0029 validation path.

## The pieces and who owns what Blazor forms validation is a small cooperation between four components and one object: | Piece | Role | |---|---| | `EditForm` | Renders the `<form>`, creates or receives an **`EditContext`** and cascades it to its children | | `EditContext` | Holds the model, which fields were modified, and every validation message | | `DataAnnotationsValidator` | Subscribes to the `EditContext` and runs DataAnnotations rules | | `ValidationMessage<TValue>` | Renders the messages for one field, chosen by its `For` expression | | `ValidationSummary` | Renders all messages as a list, or only model-level ones when given a `Model` | The **`EditContext`** is the hub. Inputs tell it when a field changes; validators listen and write messages into it; message components read from it. None of the display components validate anything themselves. ## DataAnnotationsValidator is the switch Putting `[Required]` or `[Range]` on a property does nothing in Blazor until a `DataAnnotationsValidator` sits inside the form. It is a component with no markup that, on initialization, calls `EnableDataAnnotationsValidation` on the cascaded `EditContext`. Placed outside an `EditForm`, it throws an `InvalidOperationException` because it has no `EditContext` to attach to. Once attached it reacts to two events: 1. **Field change** - an input component calls `NotifyFieldChanged`; the validator checks just that property and refreshes its messages. In an interactive form this happens while the user edits. 2. **Validation requested** - `EditContext.Validate()` raises it; the validator checks the whole object, including model-level rules, and `Validate()` returns `true` only when no message remains in any store. `EditForm` calls `Validate()` for you when it has `OnValidSubmit` or `OnInvalidSubmit` handlers, then invokes whichever matches the result. ## Showing the messages - `<ValidationMessage For="() => Volunteer.Email" />` renders each message for that field as a `div` with the `validation-message` class. - `<ValidationSummary />` renders a `ul` with the `validation-errors` class and one `li` per message, for every field. - `<ValidationSummary Model="Volunteer" />` limits the list to messages attached to the object itself, such as an `IValidatableObject` result with no member name. - A message that names no member never appears in a field's `ValidationMessage`; only a summary shows it. - Input components derived from `InputBase<TValue>` add the CSS classes `valid` or `invalid` (prefixed by `modified` once edited) and render `aria-invalid="true"` when their field has messages. ## Static and interactive forms The same markup behaves differently by render mode. In an **interactive** form, field validation runs in .NET as the user changes each input, so messages appear before submit. In a **statically rendered** form (static SSR), there is no live connection between requests: the form posts, the server rebuilds the component, validates the posted model, and re-renders with the messages. ASP.NET Core 10 offers no live field validation for static SSR forms. ## Nested objects in ASP.NET Core 10 By default `DataAnnotationsValidator` validates the **top-level** properties of the model; a `ShippingAddress` property's own `[Required]` rules are not visited. ASP.NET Core 10 adds an opt-in path: 1. Call `builder.Services.AddValidation()` in `Program.cs`. 2. Declare the model types in `.cs` files, not inside a `.razor` component, because a source generator reads them. 3. Mark the root model with `[ValidatableType]` (from `Microsoft.Extensions.Validation`, experimental in .NET 10 under diagnostic `ASP0029`). With generated metadata available, the same `DataAnnotationsValidator` validates nested objects and collection items; without it, behaviour stays as in earlier releases. ## One submit, step by step Following a single interactive submit shows how little each piece does on its own: 1. The user presses the submit button; `EditForm` handles the `submit` event. 2. With `OnValidSubmit` or `OnInvalidSubmit` set, it calls `EditContext.Validate()`. 3. `Validate()` raises `OnValidationRequested`; `DataAnnotationsValidator` clears its own message store, runs every attribute on the model, and writes the failures back keyed by field. 4. The context raises `OnValidationStateChanged`; message components and inputs re-render with the new state. 5. `Validate()` returns `false` if any store still holds a message, and `EditForm` calls the matching callback. The validator never decides which callback runs and the message components never decide what is valid: each reads or writes the shared `EditContext`. That separation is why you can add a second validator, such as one fed by a server check, without touching the display. ## Common mistakes - Expecting attributes to work without the validator component. - Putting `ValidationMessage` on a property and wondering why an object-level rule's message never shows there. - Expecting `[Remote]` to work: it is an MVC client-validation feature, unsupported in Razor components. - Assuming a static SSR form shows errors while typing.

  • Why does a message from a class-level rule appear in ValidationSummary but under no field?
    A rule on the object, such as an `IValidatableObject.Validate` result returned without member names, is stored against the model itself rather than a property. `ValidationMessage` shows only messages keyed to its `For` field, so the message surfaces only in `ValidationSummary`, either the plain one or `<ValidationSummary Model="..." />`, which shows model-level messages alone.
  • A volunteer form has an Address property whose fields carry [Required], yet an empty street passes; why, and what changes it in ASP.NET Core 10?
    `DataAnnotationsValidator` checks top-level properties only by default, so the nested object's rules are never run. In ASP.NET Core 10, call `AddValidation()`, declare the model types in `.cs` files and mark the root type `[ValidatableType]`; the generated metadata lets the same validator walk nested objects and collection items. The attribute is experimental (ASP0029).

  • Putting [Required] on the model is enough; Blazor validates it automatically.
  • ValidationMessage runs the validation rules for its field.
  • A statically rendered EditForm shows field errors while the user types.
  • DataAnnotationsValidator validates nested objects and collections by default.
  • The [Remote] attribute works in Blazor forms like it does in MVC views.

Assumes ASP.NET Core 10; nested-object and collection validation through AddValidation and [ValidatableType] is new in 10 and experimental (ASP0029).