Repository navigation
Improve Blazor async form validation - #67323
Conversation
There was a problem hiding this comment.
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. |
Optional refactor: collapse
|
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 Also, ignore the AI eliding braces and other debatable formatting choices. I'm not a monster |
Few notes:
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. |
43f37ab to
6983465
Compare
…d ValidateAsync, simplify and rename AddValidationTask
| try | ||
| { | ||
| await Task.WhenAll(tasks); | ||
| await task; |
There was a problem hiding this comment.
The design here is 2 loops:
forstart allforeachawait 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.
There was a problem hiding this comment.
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:
- 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
UnobservedTaskExceptionat some point harmless in such case. The important thing is that the exception propagates out ofValidateAsyncso that it can be spotted in dev/testing. - An exception thrown in the async validation task itself (e.g., DB exception). This is surfaced in the
foreachloop when the task is awaited and is captured as the faulted state of the validation. Nothing is orphaned in this case and noUnobservedTaskExceptionis 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Eventually, await Task.WhenAll will only throw the first exception, but at least we don't end up with UnobservedTaskExceptions.
There was a problem hiding this comment.
@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.
|
I made a small change in when the form-level 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. |
…e SSR tests resistent to other CI failures
ilonatommy
left a comment
There was a problem hiding this comment.
Mostly nits. I don't see more areas for improvement.
|
/ba-g Unrelated template test failures that fail on many recent PRs |
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:
OnValidationRequestedAsyncremovedPreview 5 added a second event,
OnValidationRequestedAsync, that async validators subscribed to with aFunc<object, ValidationRequestedEventArgs, Task>handler. That event is removed. Validators now subscribe to the existing synchronousOnValidationRequestedevent for both synchronous and asynchronous validation. To do asynchronous work, a handler registers a task factory via the newValidationRequestedEventArgs.AddValidationTask(Func<CancellationToken, Task>).ValidateAsyncinvokes every registered factory and awaits the resulting tasks.A new
ValidationRequestedEventArgs.IsAsyncproperty tells a handler whether the current pass awaits asynchronous work: it istrueforValidateAsyncandfalsefor the synchronousValidate. Registering async work whenIsAsyncisfalsethrowsInvalidOperationException, so an async validator can never be silently skipped. The cancellation token for the pass is passed directly to each factory, so theValidationRequestedEventArgs(CancellationToken)constructor and theCancellationTokenproperty added in Preview 5 are removed.ValidateandValidateAsyncare simplifiedValidate()andValidateAsync()are separate code paths.ValidateAsyncraisesOnValidationRequestedonce, 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 throwsOperationCanceledException.Validate()runs synchronous validators only: it raises theOnValidationRequestedevent withIsAsync = falsewhich means that when a handler tries to register async work viaAddValidationTask, an exception is thrown during registration, pointing the caller toValidateAsync.DataAnnotationsValidatorcan use async APIs in the BCLValidatorpath and sync APIs in the MEV pathDataAnnotationsValidatornow performs validation through the asynchronous DataAnnotations APIs, soAsyncValidationAttributeandIAsyncValidatableObjectare supported. It routes based on whether the model is registered withMicrosoft.Extensions.Validation(MEV): the MEV path usesIValidatableTypeInfo/IValidatablePropertyInfo, and the fallback path uses the staticSystem.ComponentModel.DataAnnotations.Validator. The synchronousValidate()pass uses the synchronous overloads (Validator.TryValidateObject,IValidatableTypeInfo.Validate) and the asynchronousValidateAsyncpass 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:
TrackFieldValidationThe per-field registration method is renamed from
EditContext.AddValidationTasktoEditContext.TrackFieldValidationand 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 additiveValidationRequestedEventArgs.AddValidationTask. The method now takes a factory that receives a token, andEditContextowns theCancellationTokenSourceend 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.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
HttpClientor database timeout), it is classified as an infrastructure fault rather than silently treated as success, observable viaIsValidationFaulted. App-driven cancellation through the caller's token still rethrowsOperationCanceledExceptionand 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
CancellationTokenSourcedisposal now live in one place.Tests
Unit tests were updated and extended: the
EditContextasync tests, the DataAnnotations integration tests (including async-attribute cases on both the MEV and staticValidatorpaths), and theEditFormandFieldCssClassProvidercomponent 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 theDataAnnotationsValidatorthrough both the MEV and staticValidatorpaths.Public API changes (relative to Preview 5)
Added:
Removed:
Unchanged: