Skip to content

feat(ValidateForm): add ValidateAsync method#7469

Merged
ArgoZhang merged 5 commits intomainfrom
fix-validate
Jan 4, 2026
Merged

feat(ValidateForm): add ValidateAsync method#7469
ArgoZhang merged 5 commits intomainfrom
fix-validate

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Jan 4, 2026

Link issues

fixes #7467

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add asynchronous form validation support to ValidateForm and update usages to the new API.

New Features:

  • Introduce ValidateAsync on ValidateForm to support asynchronous form validation scenarios.
  • Add an internal asynchronous validation method on BootstrapBlazorDataAnnotationsValidator that coordinates async validation results with the EditContext.

Enhancements:

  • Deprecate the synchronous Validate method on ValidateForm in favor of the new asynchronous ValidateAsync API.
  • Update table in-cell edit logic and sample components to call the asynchronous validation API before committing changes.

Tests:

  • Adjust existing component tests to use the new ValidateAsync API and verify validation behavior under asynchronous execution.

Copilot AI review requested due to automatic review settings January 4, 2026 03:22
@bb-auto bb-auto bot added the bug Something isn't working label Jan 4, 2026
@bb-auto bb-auto bot added this to the v10.2.0 milestone Jan 4, 2026
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Jan 4, 2026

Reviewer's Guide

Adds asynchronous validation support to ValidateForm via a new ValidateAsync method, wires it through the internal DataAnnotations validator with TaskCompletionSource coordination, and updates usages, samples, and tests to use the async API while marking the old sync method as obsolete.

Sequence diagram for asynchronous form validation with ValidateAsync

sequenceDiagram
    actor Developer
    participant ValidateForm
    participant DataAnnotationsValidator
    participant EditContext
    participant AsyncValidatorComponent

    Developer->>ValidateForm: ValidateAsync()
    Activate ValidateForm
    ValidateForm->>DataAnnotationsValidator: ValidateAsync()
    Activate DataAnnotationsValidator
    DataAnnotationsValidator->>DataAnnotationsValidator: create _tcs
    DataAnnotationsValidator->>EditContext: Validate()
    Note right of EditContext: Triggers validation pipeline

    EditContext->>AsyncValidatorComponent: ValidateFieldAsync()
    Activate AsyncValidatorComponent
    AsyncValidatorComponent-->>EditContext: validation result
    Deactivate AsyncValidatorComponent

    EditContext->>DataAnnotationsValidator: ValidateModel(...)
    Activate DataAnnotationsValidator
    DataAnnotationsValidator->>DataAnnotationsValidator: collect validationResults
    DataAnnotationsValidator->>EditContext: NotifyValidationStateChanged()
    DataAnnotationsValidator->>DataAnnotationsValidator: _tcs.TrySetResult(validationResults.Count == 0)
    Deactivate DataAnnotationsValidator

    DataAnnotationsValidator-->>ValidateForm: Task<bool> (await _tcs)
    Deactivate DataAnnotationsValidator
    ValidateForm-->>Developer: bool (combined result)
    Deactivate ValidateForm
Loading

Class diagram for updated ValidateForm and BootstrapBlazorDataAnnotationsValidator

classDiagram
    class ValidateForm {
        +bool Validate() %% obsolete, sync validation
        +Task~bool~ ValidateAsync()
    }

    class BootstrapBlazorDataAnnotationsValidator {
        -TaskCompletionSource~bool~ _tcs
        +Task~bool~ ValidateAsync()
        +bool Validate()
        -void AddEditContextDataAnnotationsValidation()
        -Task ValidateModel(EditContext editContext, ValidationMessageStore messages, object model, IServiceProvider provider)
        -Task ValidateField(EditContext editContext, ValidationMessageStore messages, FieldIdentifier field, IServiceProvider provider)
    }

    ValidateForm --> BootstrapBlazorDataAnnotationsValidator : uses
    BootstrapBlazorDataAnnotationsValidator --> EditContext : validates
    BootstrapBlazorDataAnnotationsValidator --> ValidationMessageStore : managesMessages
    BootstrapBlazorDataAnnotationsValidator --> FieldIdentifier : validatesField
    BootstrapBlazorDataAnnotationsValidator --> IServiceProvider : resolvesServices
Loading

File-Level Changes

Change Details Files
Introduce async validation path in the internal DataAnnotations validator and coordinate completion with the underlying EditContext validation cycle.
  • Add a TaskCompletionSource field used to await validation completion.
  • Implement internal ValidateAsync that triggers EditContext.Validate(), awaits the TaskCompletionSource task, and returns the combined synchronous and async validation result.
  • Set the TaskCompletionSource result in ValidateModel after model validation completes based on whether validation results are empty.
  • Mark the existing synchronous Validate method as excluded from code coverage.
src/BootstrapBlazor/Components/ValidateForm/BootstrapBlazorDataAnnotationsValidator.cs
Expose ValidateAsync on ValidateForm and deprecate the existing synchronous Validate API.
  • Change public Validate() to be marked Obsolete with guidance to use ValidateAsync and exclude it from code coverage.
  • Add public Task ValidateAsync() that delegates to the validator’s ValidateAsync().
src/BootstrapBlazor/Components/ValidateForm/ValidateForm.razor.cs
Update components, samples, and tests to call the new async validation API instead of the obsolete sync method.
  • Change test cases to await ValidateForm.ValidateAsync using bUnit’s InvokeAsync where appropriate.
  • Adjust sample components’ validate handlers to be async Task methods that await ValidateAsync.
  • Update Table in-cell edit flow to await _inCellValidateForm.ValidateAsync() and early-return when invalid.
  • Ensure event invocations (e.g., clicking clear buttons) are performed via InvokeAsync to align with async validation.
test/UnitTest/Components/DateTimeRangeTest.cs
test/UnitTest/Components/InputNumberTest.cs
test/UnitTest/Components/DateTimePickerTest.cs
src/BootstrapBlazor.Server/Components/Samples/ValidateForms.razor.cs
src/BootstrapBlazor.Server/Components/Samples/Cascaders.razor.cs
src/BootstrapBlazor/Components/Table/Table.razor.Edit.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#7467 Fix ValidateForm manual validation so that it correctly reflects validation state for components with asynchronous validation (e.g., CardUpload), returning false when validation ultimately fails instead of always returning true.
#7467 Expose and propagate an asynchronous validation API (ValidateAsync) on ValidateForm and its underlying validator, and update internal usages/tests to rely on this async API instead of the previous synchronous Validate method.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@ArgoZhang ArgoZhang merged commit 620fafe into main Jan 4, 2026
6 of 8 checks passed
@ArgoZhang ArgoZhang deleted the fix-validate branch January 4, 2026 03:23
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Consider handling concurrent calls to ValidateAsync on BootstrapBlazorDataAnnotationsValidator more defensively (e.g., rejecting a second call while one is in flight or using a new local TaskCompletionSource per call) to avoid multiple callers sharing the same _tcs instance and getting unexpected results.
  • After ValidateModel completes and _tcs.TrySetResult(...) is invoked, you may want to reset _tcs to null to avoid holding onto a completed TaskCompletionSource longer than needed and to make misuse (e.g., accidentally reusing the same instance) more obvious.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider handling concurrent calls to `ValidateAsync` on `BootstrapBlazorDataAnnotationsValidator` more defensively (e.g., rejecting a second call while one is in flight or using a new local `TaskCompletionSource` per call) to avoid multiple callers sharing the same `_tcs` instance and getting unexpected results.
- After `ValidateModel` completes and `_tcs.TrySetResult(...)` is invoked, you may want to reset `_tcs` to `null` to avoid holding onto a completed `TaskCompletionSource` longer than needed and to make misuse (e.g., accidentally reusing the same instance) more obvious.

## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/Components/ValidateForm/BootstrapBlazorDataAnnotationsValidator.cs:55-60` </location>
<code_context>
     /// 手动验证表单方法
     /// </summary>
     /// <returns></returns>
+    internal async Task<bool> ValidateAsync()
+    {
+        _tcs = new(false);
+        var ret = CurrentEditContext.Validate();
+        var valid = await _tcs.Task;
+        return ret && valid;
+    }
+
</code_context>

<issue_to_address>
**issue (bug_risk):** Avoid potential races when multiple concurrent ValidateAsync calls share a single TaskCompletionSource field.

Since `_tcs` is a single field, concurrent `ValidateAsync` calls will overwrite each other’s TCS. The last call wins, and earlier callers may await a task that is never (or incorrectly) completed, causing hangs or incorrect validation results when multiple validations run in parallel.

Consider either preventing concurrent `ValidateAsync` calls (e.g., lock/guard/throw) or using a per-call TCS that’s wired into the validation flow instead of a shared field, so behavior remains correct even if calls overlap.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@codecov
Copy link
Copy Markdown

codecov bot commented Jan 4, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (f71821f) to head (98312fc).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #7469   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          749       749           
  Lines        32912     32922   +10     
  Branches      4573      4574    +1     
=========================================
+ Hits         32912     32922   +10     
Flag Coverage Δ
BB 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds asynchronous validation support to the ValidateForm component by introducing a new ValidateAsync method and deprecating the synchronous Validate method. This change enables proper support for components that require asynchronous validation.

Key changes:

  • Added ValidateAsync() method to ValidateForm that supports asynchronous validation
  • Marked the existing synchronous Validate() method as obsolete
  • Updated all internal usages, tests, and samples to use the new async method

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/BootstrapBlazor/Components/ValidateForm/ValidateForm.razor.cs Added public ValidateAsync() method and marked Validate() as obsolete
src/BootstrapBlazor/Components/ValidateForm/BootstrapBlazorDataAnnotationsValidator.cs Implemented internal ValidateAsync() with TaskCompletionSource to support async validation flow
src/BootstrapBlazor/Components/Table/Table.razor.Edit.cs Updated InCell validation to use ValidateAsync()
test/UnitTest/Components/InputNumberTest.cs Updated test to use ValidateAsync() instead of Validate()
test/UnitTest/Components/DateTimeRangeTest.cs Updated test to use ValidateAsync() and properly await validation calls
test/UnitTest/Components/DateTimePickerTest.cs Updated test to use ValidateAsync()
src/BootstrapBlazor.Server/Components/Samples/ValidateForms.razor.cs Updated sample code to demonstrate ValidateAsync() usage
src/BootstrapBlazor.Server/Components/Samples/Cascaders.razor.cs Updated sample code to use ValidateAsync()
src/BootstrapBlazor/BootstrapBlazor.csproj Version bumped to 10.2.1-beta05

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

/// <summary>
/// 异步验证方法 用于代码调用触发表单验证(支持异步验证)
/// </summary>
/// <returns></returns>
Copy link

Copilot AI Jan 4, 2026

Choose a reason for hiding this comment

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

The XML documentation is incomplete. The returns tag on line 661 is empty and should describe what the method returns. It should specify that it returns a Task that resolves to true if validation succeeds, false otherwise.

Suggested change
/// <returns></returns>
/// <returns>A Task that resolves to true if validation succeeds; otherwise, false.</returns>

Copilot uses AI. Check for mistakes.
Comment on lines +50 to +61
private TaskCompletionSource<bool>? _tcs;
/// <summary>
/// 手动验证表单方法
/// </summary>
/// <returns></returns>
internal async Task<bool> ValidateAsync()
{
_tcs = new(false);
var ret = CurrentEditContext.Validate();
var valid = await _tcs.Task;
return ret && valid;
}
Copy link

Copilot AI Jan 4, 2026

Choose a reason for hiding this comment

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

The _tcs field is not thread-safe and can cause race conditions. If ValidateAsync() is called multiple times concurrently or before a previous validation completes, the field will be overwritten and the previous caller will await a task that never completes or receives the wrong result. Consider using a local variable for the TaskCompletionSource instead, or implement proper synchronization to prevent concurrent validations.

Copilot uses AI. Check for mistakes.
/// <returns></returns>
internal async Task<bool> ValidateAsync()
{
_tcs = new(false);
Copy link

Copilot AI Jan 4, 2026

Choose a reason for hiding this comment

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

The TaskCompletionSource constructor is being called with a boolean argument 'false'. In modern .NET, TaskCompletionSource constructors accept TaskCreationOptions, not a boolean. The boolean parameter doesn't exist. This should likely be 'new TaskCompletionSource()' or 'new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)' to avoid synchronous continuations.

Suggested change
_tcs = new(false);
_tcs = new(System.Threading.Tasks.TaskCreationOptions.RunContinuationsAsynchronously);

Copilot uses AI. Check for mistakes.
Comment on lines +110 to +112
if (_tcs != null)
{
_tcs.TrySetResult(validationResults.Count == 0);
Copy link

Copilot AI Jan 4, 2026

Choose a reason for hiding this comment

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

The _tcs field check and result setting should handle the case where the field might be null. While the current implementation sets _tcs in ValidateAsync(), the ValidateModel method can also be called from OnValidationRequested event handler (line 83) where _tcs would be null. This creates inconsistent behavior - the TaskCompletionSource is only set when validation is triggered via ValidateAsync(), not when triggered by the EditContext's validation events.

Suggested change
if (_tcs != null)
{
_tcs.TrySetResult(validationResults.Count == 0);
// Safely complete any pending TaskCompletionSource associated with this validation.
var tcs = _tcs;
if (tcs != null)
{
tcs.TrySetResult(validationResults.Count == 0);
_tcs = null;

Copilot uses AI. Check for mistakes.
Comment on lines 52 to 54
/// 手动验证表单方法
/// </summary>
/// <returns></returns>
Copy link

Copilot AI Jan 4, 2026

Choose a reason for hiding this comment

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

The XML documentation summary "手动验证表单方法" (Manual form validation method) is insufficient. It should describe what the method returns and clarify that it performs asynchronous validation. Consider adding a returns tag explaining that it returns a Task that resolves to true if validation succeeds, false otherwise.

Suggested change
/// 手动验证表单方法
/// </summary>
/// <returns></returns>
/// 手动异步验证表单方法,执行表单的异步验证并返回验证结果。
/// </summary>
/// <returns>一个 <see cref="Task{Boolean}"/>,当验证完成时为 true 表示验证成功,否则为 false。</returns>

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(ValidateForm): Validate 方法遇到异步验证时始终方法 true

2 participants