Skip to content

Improve Blazor async form validation - #67323

Merged
oroztocil merged 23 commits into
mainfrom
oroztocil/validation-async-improvements
Jul 7, 2026
Merged

oroztocil merged 23 commits into
mainfrom
oroztocil/validation-async-improvements

Conversation

@oroztocil

@oroztocil oroztocil commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

This PR refines the async form validation support added to Blazor in .NET 11 Preview 5 (#66526). It addresses the review feedback from that PR and makes several related improvements discussed since then. The notes below describe what changes relative to what Preview 5 shipped.

Single validation event: OnValidationRequestedAsync removed

Preview 5 added a second event, OnValidationRequestedAsync, that async validators subscribed to with a Func<object, ValidationRequestedEventArgs, Task> handler. That event is removed. Validators now subscribe to the existing synchronous OnValidationRequested event for both synchronous and asynchronous validation. To do asynchronous work, a handler registers a task factory via the new ValidationRequestedEventArgs.AddValidationTask(Func<CancellationToken, Task>). ValidateAsync invokes every registered factory and awaits the resulting tasks.

A new ValidationRequestedEventArgs.IsAsync property tells a handler whether the current pass awaits asynchronous work: it is true for ValidateAsync and false for the synchronous Validate. Registering async work when IsAsync is false throws InvalidOperationException, so an async validator can never be silently skipped. The cancellation token for the pass is passed directly to each factory, so the ValidationRequestedEventArgs(CancellationToken) constructor and the CancellationToken property added in Preview 5 are removed.

// Removed:
public event Func<object, ValidationRequestedEventArgs, Task>? EditContext.OnValidationRequestedAsync;
public ValidationRequestedEventArgs(CancellationToken cancellationToken);
public CancellationToken ValidationRequestedEventArgs.CancellationToken { get; }

// Added on ValidationRequestedEventArgs:
public bool IsAsync { get; }
public void AddValidationTask(Func<CancellationToken, Task> validate);

// Validator usage:
editContext.OnValidationRequested += (sender, args) =>
{
    if (args.IsAsync)
    {
        args.AddValidationTask(token => ValidateModelAsync(editContext.Model, token));
    }
    else
    {
        // Validator can decide whether to perform sync work or throw
        throw new InvalidOperationException("This validator cannot be used for synchronous validation. Use EditContext.ValidateAsync instead.");
    }
};

Validate and ValidateAsync are simplified

Validate() and ValidateAsync() are separate code paths. ValidateAsync raises OnValidationRequested once, invokes all registered factories so the validators run concurrently, and then awaits them; the caller's token is passed to each factory and a cancelled token throws OperationCanceledException.

Validate() runs synchronous validators only: it raises the OnValidationRequested event with IsAsync = false which means that when a handler tries to register async work via AddValidationTask, an exception is thrown during registration, pointing the caller to ValidateAsync.

DataAnnotationsValidator can use async APIs in the BCL Validator path and sync APIs in the MEV path

DataAnnotationsValidator now performs validation through the asynchronous DataAnnotations APIs, so AsyncValidationAttribute and IAsyncValidatableObject are supported. It routes based on whether the model is registered with Microsoft.Extensions.Validation (MEV): the MEV path uses IValidatableTypeInfo/IValidatablePropertyInfo, and the fallback path uses the static System.ComponentModel.DataAnnotations.Validator. The synchronous Validate() pass uses the synchronous overloads (Validator.TryValidateObject, IValidatableTypeInfo.Validate) and the asynchronous ValidateAsync pass uses the async overloads (Validator.TryValidateObjectAsync, IValidatableTypeInfo.ValidateAsync). These complete synchronously for sync-only attributes, so all existing synchronous DataAnnotations behavior is unchanged.

Per-field registration: TrackFieldValidation

The per-field registration method is renamed from EditContext.AddValidationTask to EditContext.TrackFieldValidation and reshaped. The new name reflects that the operation is not additive (a new validation cancels and supersedes the field's current pending validation) and disambiguates it from the additive ValidationRequestedEventArgs.AddValidationTask. The method now takes a factory that receives a token, and EditContext owns the CancellationTokenSource end to end, so callers no longer construct and hand over a task plus a CTS (and remember not to dispose it). The previous low-level overload is removed since linking inside the factory covers the advanced scenarios.

// Before (Preview 5):
public void AddValidationTask(in FieldIdentifier field, Task task, CancellationTokenSource cts);

// After:
public void TrackFieldValidation(in FieldIdentifier field, Func<CancellationToken, Task> validate);

// Validator usage:
editContext.OnFieldChanged += (sender, args) =>
    editContext.TrackFieldValidation(args.FieldIdentifier, token => ValidateFieldAsync(args.FieldIdentifier, token));

Cancellation from an unrelated source is treated as a fault

When a validation task completes canceled by something other than the caller's token or our own supersession (for example an HttpClient or database timeout), it is classified as an infrastructure fault rather than silently treated as success, observable via IsValidationFaulted. App-driven cancellation through the caller's token still rethrows OperationCanceledException and is not a fault.

Internal: unified per-field state machine

The two separate code paths for completed versus in-flight per-field tasks were collapsed into a single observer, leveraging the fact that awaiting an already-completed task resumes synchronously. The pending/faulted state, change notifications, supersession, and CancellationTokenSource disposal now live in one place.

Tests

Unit tests were updated and extended: the EditContext async tests, the DataAnnotations integration tests (including async-attribute cases on both the MEV and static Validator paths), and the EditForm and FieldCssClassProvider component tests. New end-to-end tests cover the async validation UX in the browser, in both interactive (Server and WebAssembly) and static SSR rendering: per-field pending, faulted, and supersession transitions; form-level validation on submit; and the DataAnnotationsValidator through both the MEV and static Validator paths.

Public API changes (relative to Preview 5)

Added:

+ValidationRequestedEventArgs.IsAsync.get -> bool
+ValidationRequestedEventArgs.AddValidationTask(Func<CancellationToken, Task!>! validate) -> void
+EditContext.TrackFieldValidation(in FieldIdentifier fieldIdentifier, Func<CancellationToken, Task!>! validate) -> void

Removed:

-EditContext.OnValidationRequestedAsync -> Func<object!, ValidationRequestedEventArgs!, Task!>?
-EditContext.AddValidationTask(in FieldIdentifier fieldIdentifier, Task! task, CancellationTokenSource! cts) -> void
-ValidationRequestedEventArgs.ValidationRequestedEventArgs(CancellationToken cancellationToken) -> void
-ValidationRequestedEventArgs.CancellationToken.get -> CancellationToken

Unchanged:

EditContext.ValidateAsync(CancellationToken cancellationToken = default) -> Task<bool>!
EditContext.IsValidationPending(in FieldIdentifier fieldIdentifier) -> bool
EditContext.IsValidationPending<TField>(Expression<Func<TField>!>! accessor) -> bool
EditContext.IsValidationPending() -> bool
EditContext.IsValidationFaulted(in FieldIdentifier fieldIdentifier) -> bool
EditContext.IsValidationFaulted<TField>(Expression<Func<TField>!>! accessor) -> bool
EditContext.IsValidationFaulted() -> bool

Copilot AI review requested due to automatic review settings June 19, 2026 19:14
@oroztocil
oroztocil requested a review from a team as a code owner June 19, 2026 19:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Refines Blazor async form validation by consolidating validation onto the existing EditContext.OnValidationRequested event, enabling async work via task registration on ValidationRequestedEventArgs, and improving fault/cancellation surfacing (including per-field and form-level exceptions).

Changes:

  • Replace the dual validation-event model with a single sync event plus ValidationRequestedEventArgs.AddValidationTask(Task) for async validation.
  • Rename/reshape per-field async validation tracking to EditContext.TrackFieldValidation(...) with framework-owned cancellation/cleanup and exception retrieval APIs.
  • Update DataAnnotations and component/unit tests to cover async validation, pending/faulted state, and exception propagation/containment.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/Components/Web/test/Forms/Helpers/TestAsyncValidatorComponent.cs Updates test helper to register async validation via AddValidationTask and per-field via TrackFieldValidation.
src/Components/Web/test/Forms/FieldCssClassProviderTest.cs Migrates tests to TrackFieldValidation for pending/faulted CSS class assertions.
src/Components/Web/test/Forms/EditFormTest.cs Updates submit behavior tests to the new per-field tracking API and token cancellation model.
src/Components/Web/src/Forms/FieldCssClassProvider.cs Updates docs to reference TrackFieldValidation for pending CSS behavior.
src/Components/Forms/test/Helpers/TestAsyncValidator.cs Updates test helper to new validation/task registration APIs.
src/Components/Forms/test/EditContextDataAnnotationsExtensionsTest.cs Adds/updates DataAnnotations integration tests covering async validation attributes and fault behavior.
src/Components/Forms/test/EditContextAsyncTest.cs Updates and expands async validation unit tests for new event/task registration and exception surfacing semantics.
src/Components/Forms/src/ValidationRequestedEventArgs.cs Adds task collection + AddValidationTask(Task) API (and read-only Empty semantics).
src/Components/Forms/src/PublicAPI.Unshipped.txt Records new public APIs (AddValidationTask, TrackFieldValidation, exception getters).
src/Components/Forms/src/FieldState.cs Changes per-field fault tracking from bool to stored exception.
src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs Routes DataAnnotations through async-capable APIs and registers form validation as a task.
src/Components/Forms/src/EditContext.cs Removes async event, implements task-registration pipeline, adds exception retrieval APIs, and new per-field tracking method.

Comment thread src/Components/Forms/src/EditContext.cs Resolved
@oroztocil oroztocil changed the title Async form validation: review follow-ups and refinements Improve Blazor async form validation Jun 19, 2026
@oroztocil
oroztocil requested a review from javiercn June 19, 2026 19:48
@oroztocil oroztocil added the area-blazor Includes: Blazor, Razor Components label Jun 19, 2026
@oroztocil oroztocil added this to the 11.0-preview6 milestone Jun 19, 2026
Comment thread src/Components/Forms/src/EditContext.cs Resolved
@javiercn

javiercn commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

Optional refactor: collapse Validate / ValidateAsync onto one algorithm

The current PR carries two hand-written task-handling paths (Validate and ValidateAsync) that already share RaiseValidationRequested and ObserveFormValidationTasks, but still duplicate the start/await/classify/return scaffolding and keep two slightly different shapes that can drift. A small restructuring removes the duplication while keeping observable behavior identical.

Idea: both public entries delegate to one private ValidateAsync(ValidationRequestedEventArgs args, CancellationToken) that holds the whole algorithm. The per-pass result lives on the (internal) args.Result, so neither entry needs the task's value and there is no GetAwaiter().GetResult() anywhere. An internal args.NotifyPending flag marks the asynchronous entry: it gates the pending notifications and is what lets the synchronous entry stay side-effect free. Validate just calls the core and either reads args.Result or throws.

public bool Validate()
{
    var args = new ValidationRequestedEventArgs();                 // NotifyPending defaults to false
    var task = ValidateAsync(args, CancellationToken.None);
    if (!task.IsCompleted)
    {
        throw new InvalidOperationException(
            $"An asynchronous validation handler did not complete synchronously. Use {nameof(ValidateAsync)} instead.");
    }
    return args.Result;
}

public Task<bool> ValidateAsync(CancellationToken cancellationToken = default)
{
    var args = new ValidationRequestedEventArgs(cancellationToken) { NotifyPending = true };
    var task = ValidateAsync(args, cancellationToken);
    return task.IsCompletedSuccessfully ? Task.FromResult(args.Result) : Awaited(task, args);

    static async Task<bool> Awaited(Task t, ValidationRequestedEventArgs a) { await t; return a.Result; }
}

// Single source of truth. Not async: the synchronous happy path returns a completed task with no
// state machine and no Task.WhenAll; only genuinely pending work goes through ObserveValidationTasks.
private Task ValidateAsync(ValidationRequestedEventArgs args, CancellationToken cancellationToken)
{
    if (args.NotifyPending)
    {
        CancelAllPendingValidationTasks();
        _isFormValidationPending = true;
        NotifyValidationStateChanged();
    }

    try
    {
        RaiseValidationRequested(args);
        var tasks = args.ValidationTasks;

        for (var i = 0; i < tasks.Count; i++)
        {
            if (!tasks[i].IsCompleted)
            {
                return ObserveValidationTasks(args, tasks, cancellationToken);   // same call for both entries
            }
        }

        Finish(args, tasks);                                                     // ObserveFormValidationTasks + set args.Result
    }
    catch
    {
        // A synchronous handler threw: clear the pending flag we set above before the exception escapes.
        if (args.NotifyPending) { _isFormValidationPending = false; NotifyValidationStateChanged(); }
        throw;
    }

    if (args.NotifyPending) { _isFormValidationPending = false; NotifyValidationStateChanged(); }
    return Task.CompletedTask;
}

private async Task ObserveValidationTasks(ValidationRequestedEventArgs args, IReadOnlyList<Task> tasks, CancellationToken cancellationToken)
{
    try
    {
        try { await Task.WhenAll(tasks); } catch { /* per-task outcomes classified in Finish */ }

        // Synchronous entry awaited only to observe faults; Validate() already threw on the incomplete
        // task it saw. Return without classifying or notifying, so Validate() stays side-effect free.
        if (!args.NotifyPending) { return; }

        cancellationToken.ThrowIfCancellationRequested();   // caller cancellation propagates, prior fault preserved
        Finish(args, tasks);
    }
    finally
    {
        if (args.NotifyPending) { _isFormValidationPending = false; NotifyValidationStateChanged(); }
    }
}

private void Finish(ValidationRequestedEventArgs args, IReadOnlyList<Task> tasks)
{
    var faulted = ObserveFormValidationTasks(tasks);              // writes _formValidationException
    args.Result = !faulted && !GetValidationMessages().Any();
}

Why this is behavior-preserving

  • Validate stays inert: it never runs the pending/field-cancellation ceremony, and on incomplete work ObserveValidationTasks awaits only to observe faults (no UnobservedTaskException) and returns before Finish, so it mutates no state and fires no notification. State-wise this matches the previous ObserveOrphanedTasks behavior.
  • A synchronous handler exception still propagates synchronously from both entry points (the core is not async).
  • Validator faults stay contained (classified into _formValidationException); caller cancellation still propagates via ThrowIfCancellationRequested with the previous fault preserved.

Why it is worth it

  • One classification path and one result projection, so the two methods cannot drift; one branch in the core loop.
  • The synchronous happy path (everything completes synchronously) allocates no Task.WhenAll and no async state machine, and returns a cached Task<bool>.
  • The result is read from args.Result, so there is no GetAwaiter().GetResult() anywhere.

Notes / tradeoffs

  • Two internal members on ValidationRequestedEventArgs (Result and NotifyPending). Keep them internal: they are infrastructure state and should not leak into the public validator-facing API.
  • Because the core is non-async, it uses one try/catch to clear the pending flag if a handler throws synchronously on the async entry (a fully-async core would get that from a single try/finally, but would force Validate to use GetAwaiter().GetResult() to resurface a synchronous handler exception).
  • On the Validate()-with-incomplete-tasks path (the misuse path that throws), observing faults now rides on await Task.WhenAll rather than per-task continuations, a negligible allocation since that path throws anyway.

@oroztocil

oroztocil commented Jun 22, 2026 •

Copy link
Copy Markdown
Member Author

@javiercn

Optional refactor: collapse Validate / ValidateAsync onto one algorithm

I played around with unifying Validate and ValidateAsync more but have not tried this approach. I will need to think it through a bit more but I like it in principle.

@javiercn

javiercn commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

@javiercn

Optional refactor: collapse Validate / ValidateAsync onto one algorithm

I played around with unifying Validate and ValidateAsync more but have not tried this approach. I will need to think it through a bit more but I like it in principle.

This is the AI being the AI. It's not optional, it's my curated strong suggestion.

The code is significantly simpler to read this way and avoids shennanigans like task.ContinueWith that takes us out of the sync context (even if in this case it was only to swallow the exception)

Also, ignore the AI eliding braces and other debatable formatting choices. I'm not a monster

@oroztocil

Copy link
Copy Markdown
Member Author

@javiercn

Optional refactor: collapse Validate / ValidateAsync onto one algorithm

I played around with unifying Validate and ValidateAsync more but have not tried this approach. I will need to think it through a bit more but I like it in principle.

This is the AI being the AI. It's not optional, it's my curated strong suggestion.

The code is significantly simpler to read this way and avoids shennanigans like task.ContinueWith that takes us out of the sync context (even if in this case it was only to swallow the exception)

Also, ignore the AI eliding braces and other debatable formatting choices. I'm not a monster

Few notes:

  • "significantly simpler to read" is subjective because this adds more logic elsewhere
  • the analysis might have been written against an older version of the implementation because it mentions GetAwaiter().GetResult() few times which is not used in the code
  • the two implementations are not equivalent in some minor behavioral aspects:
    • sync handler exception not being captured in returned task from ValidateAsync
    • not checking for already cancelled tokens
    • not observing some orphaned tasks (sync handler throws after an earlier handler registered a task)

However, I like the shared classification path and have adopted the workflow you propose with few small tweaks. Additional feedback is appreciated.

I also added more tests - these might not be fully ready.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 28 out of 28 changed files in this pull request and generated 2 comments.

Comment thread src/Components/Forms/src/EditContext.cs Resolved
Comment thread src/Components/Forms/src/EditContext.cs Resolved
@oroztocil
oroztocil force-pushed the oroztocil/validation-async-improvements branch from 43f37ab to 6983465 Compare June 26, 2026 14:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 29 out of 29 changed files in this pull request and generated no new comments.

Comment thread src/Components/Forms/src/EditContext.cs Outdated
try
{
await Task.WhenAll(tasks);
await task;

@ilonatommy ilonatommy Jun 30, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The design here is 2 loops:

  • for start all
  • foreach await all.

It might happen that we have task1 queued that returned a real running task. After it there's task2 that throws an exception immidiately in loop1 from some reason. If task1's async job finishes with exception later, it will produce UnobservedTaskException because we didn't await it.

@oroztocil oroztocil Jun 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a deliberate choice that I made. I previously had logic for observing orphaned tasks here but decided to simplify it.

My reasoning is that we can distinguish two classes of problems:

  1. The task factory returning null or throwing synchronously => I consider this a programming bug. I want to fail loudly here because that should not happen ever in a non-development scenario. I consider seeing UnobservedTaskException at some point harmless in such case. The important thing is that the exception propagates out of ValidateAsync so that it can be spotted in dev/testing.
  2. An exception thrown in the async validation task itself (e.g., DB exception). This is surfaced in the foreach loop when the task is awaited and is captured as the faulted state of the validation. Nothing is orphaned in this case and no UnobservedTaskException is raised.

We can discuss if this is the correct behavior - I just wanted to say that it is not an oversight but it is intentional. It should also be noted that the UnobservedTaskException scenario can happen only if all of these are true:

  • multiple async validation tasks are registered (our DataAnnotations registers a single task per validation pass),
  • a later factory throws synchronously / returns null (a programming bug),
  • while an earlier factory returned a genuinely async running task that later faults.

That said, I can put the orphan observation logic back in if needed (while keeping the rest the same). It just did not felt worth it for the buggy edge case, considering the task handling simplification that we were trying to achieve with @javiercn.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In MEV, we captured all synchronously-produced exceptions and transformed them to faulted tasks via Task.FromException, and move forward as if the exception was thrown asynchronously.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eventually, await Task.WhenAll will only throw the first exception, but at least we don't end up with UnobservedTaskExceptions.

@oroztocil oroztocil Jun 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Youssef1313 I also had that behavior at this level but realized that it would mask programming bugs as faulted validations and makes for worse DX. To reiterate, here a sync exception means the task factory itself throws - e.g. the code that would call into MEV. I would argue such code should never throw and if that happens, the interested audience is the developer, not the app user.

@oroztocil

oroztocil commented Jul 1, 2026 •

Copy link
Copy Markdown
Member Author

I made a small change in when the form-level ValidateAsync notifies change to the pending state. Now it only notifies if some of the validation tasks does not complete synchronously. This prevents spurious state change notifications and UI flashes (that could happen in specific cases, even with render batching). The field-level validation already had such check.

Note that this is a purely UI thing used on the async path. There is no check of this sort on the sync path which uses sync DataAnnotations/MEV APIs only.

@ilonatommy ilonatommy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly nits. I don't see more areas for improvement.

@oroztocil

Copy link
Copy Markdown
Member Author

/ba-g Unrelated template test failures that fail on many recent PRs

@dariatiurina dariatiurina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Repprove

@oroztocil
oroztocil merged commit b126e4f into main Jul 7, 2026
24 of 25 checks passed
@oroztocil
oroztocil deleted the oroztocil/validation-async-improvements branch July 7, 2026 16:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants