ASP.NET Core Blazor 進階表單驗證

Note

這不是本文的最新版本。 目前版本請參閱本文的 .NET 11 版本。

Warning

此版本的 ASP.NET Core 已不再受支援。 如需詳細資訊,請參閱 .NET 和 .NET Core 支援政策。 關於目前版本,請參閱 本文的 .NET 10 版本。

本文展示可重用驗證器元件與遠端驗證。 關於常見的表單驗證 API,包括資料註解、直接EditContext驗證、訊息顯示、樣式、狀態及提交行為,請參見 ASP.NET Core Blazor 表單驗證。

關於由 Blazor Minimal API 共享的基於模型的驗證規則,請參見 ASP.NET Core 中的驗證。

關於靜態伺服器端渲染(static SSR)中的瀏覽器驗證,請參見 ASP.NET Core Blazor 靜態 SSR 中的客戶端表單驗證。

建立一個驗證器元件

驗證器元件封裝了使用表單 EditContext 和 ValidationMessageStore 的驗證。 當多個表單採用相同的驗證行為,或錯誤來自服務而非模型上的驗證屬性時,這非常有用。

組件:

  • 接收表單的 EditContext 作為串聯參數。
  • 建立錯誤訊息儲存庫。
  • 當要求驗證時,能清除陳舊的表單錯誤。
  • 當欄位變更時,清除該欄位中過時的錯誤。
  • 揭露顯示與清除錯誤的方法。
  • 當事件處理程序被處理時,會取消訂閱。

CustomValidation.razor:

@implements IDisposable

@code {
    [CascadingParameter]
    private EditContext? CurrentEditContext { get; set; }

    private ValidationMessageStore messages = default!;

    protected override void OnInitialized()
    {
        if (CurrentEditContext is null)
        {
            throw new InvalidOperationException(
                "CustomValidation requires a cascading EditContext.");
        }

        messages = new ValidationMessageStore(CurrentEditContext);
        CurrentEditContext.OnValidationRequested +=
            HandleValidationRequested;
        CurrentEditContext.OnFieldChanged += HandleFieldChanged;
    }

    public void DisplayErrors(IDictionary<string, string[]> errors)
    {
        foreach (var error in errors)
        {
            messages.Add(
                CurrentEditContext!.Field(error.Key),
                error.Value);
        }

        CurrentEditContext!.NotifyValidationStateChanged();
    }

    public void ClearErrors()
    {
        messages.Clear();
        CurrentEditContext!.NotifyValidationStateChanged();
    }

    private void HandleValidationRequested(
        object? sender, ValidationRequestedEventArgs e) =>
        ClearErrors();

    private void HandleFieldChanged(
        object? sender, FieldChangedEventArgs e)
    {
        messages.Clear(e.FieldIdentifier);
        CurrentEditContext!.NotifyValidationStateChanged();
    }

    public void Dispose()
    {
        if (CurrentEditContext is not null)
        {
            CurrentEditContext.OnValidationRequested -=
                HandleValidationRequested;
            CurrentEditContext.OnFieldChanged -= HandleFieldChanged;
        }
    }
}

將元件放在 EditForm 內,並在表單或服務需要顯示錯誤時擷取元件參考:

<EditForm Model="Model" OnValidSubmit="Submit">
    <DataAnnotationsValidator />
    <CustomValidation @ref="customValidation" />
    <ValidationSummary />

    ...
</EditForm>

@code {
    private CustomValidation? customValidation;
}

該組件可與 DataAnnotationsValidator並用。 每個驗證者都有自己與同一個 EditContext 相關聯的訊息儲存區,而 ValidationMessage 和 ValidationSummary 會顯示來自兩個驗證者的訊息。

若要在驗證器元件中實作商業規則,而非接受外部錯誤,請從 或 HandleFieldChanged 執行該規則HandleValidationRequested並將其訊息加入 messages。 若想看一個直接在表單元件中執行此操作的小範例,請參見 ASP.NET Core Blazor 表單驗證。

新增非同步驗證

相同的元件模式支援非同步工作:

  • 在 OnValidationRequested 處理常式中,呼叫 e.AddAsyncValidator 以註冊表單層級的工作。 EditForm 會先等待其完成,再呼叫 OnValidSubmit 或 OnInvalidSubmit。
  • 在 OnFieldChanged 處理常式中,呼叫 EditContext.RegisterAsyncFieldValidator 來啟動該欄位的驗證。 對同一欄位開始另一個驗證會取代並取消先前的操作。

針對表單層級的非同步驗證:

private void HandleValidationRequested(
    object? sender, ValidationRequestedEventArgs e) =>
    e.AddAsyncValidator(ValidateAsync);

private async Task ValidateAsync(CancellationToken cancellationToken)
{
    var field = CurrentEditContext!.Field(nameof(Model.Username));
    messages.Clear(field);

    var available = await Http.GetFromJsonAsync<bool>(
        $"api/usernames/available?value={Uri.EscapeDataString(Model.Username)}",
        cancellationToken);

    if (!available)
    {
        messages.Add(field, "The username is already taken.");
    }

    CurrentEditContext.NotifyValidationStateChanged();
}

對於現場層級非同步驗證:

private void HandleFieldChanged(
    object? sender, FieldChangedEventArgs e)
{
    CurrentEditContext!.RegisterAsyncFieldValidator(
        e.FieldIdentifier,
        token => ValidateFieldAsync(e.FieldIdentifier, token));
}

將提供的取消令牌傳給 I/O。 在開始操作前清除先前訊息,例外後避免發布部分結果,並在更新訊息後呼叫 NotifyValidationStateChanged 。

因被取代或驗證通過被取消而被取消的操作會被丟棄。 其他例外情況則將欄位或型態置於錯誤狀態。 關於顯示待處理及錯誤狀態,請參見 ASP.NET Core Blazor 表單驗證。

若要結合表單層級與每欄位非同步驗證的完整元件,請參考以下範例:

@implements IDisposable
@inject HttpClient Http

@* A validator component that runs asynchronous validation, both when the whole form is
   validated on submit and per field as the user edits the Username field. *@

@code {
    [CascadingParameter]
    private EditContext? CurrentEditContext { get; set; }

    [Parameter, EditorRequired]
    public RegistrationModel Model { get; set; } = default!;

    private ValidationMessageStore? messages;

    protected override void OnInitialized()
    {
        ArgumentNullException.ThrowIfNull(CurrentEditContext);
        messages = new ValidationMessageStore(CurrentEditContext);
        CurrentEditContext.OnValidationRequested += OnValidationRequested;
        CurrentEditContext.OnFieldChanged += OnFieldChanged;
    }

    // Registers asynchronous work for the whole form. EditForm awaits it before invoking
    // OnValidSubmit.
    private void OnValidationRequested(
        object? sender, ValidationRequestedEventArgs e) =>
        e.AddAsyncValidator(ValidateUsernameAsync);

    // Registers asynchronous work for a single field. A new registration supersedes and
    // cancels any validation already in flight for the field.
    private void OnFieldChanged(object? sender, FieldChangedEventArgs e)
    {
        if (e.FieldIdentifier.FieldName != nameof(RegistrationModel.Username))
        {
            return;
        }

        CurrentEditContext!.RegisterAsyncFieldValidator(
            e.FieldIdentifier,
            token => CheckAsync(e.FieldIdentifier, token));
    }

    private Task ValidateUsernameAsync(CancellationToken token) =>
        CheckAsync(CurrentEditContext!.Field(nameof(Model.Username)), token);

    private async Task CheckAsync(FieldIdentifier field, CancellationToken token)
    {
        messages!.Clear(field);

        var available = await Http.GetFromJsonAsync<bool>(
            $"api/usernames/available?value={Uri.EscapeDataString(Model.Username)}",
            token);

        if (!available)
        {
            messages.Add(field, "The username is already taken.");
        }

        CurrentEditContext!.NotifyValidationStateChanged();
    }

    public void Dispose()
    {
        if (CurrentEditContext is not null)
        {
            CurrentEditContext.OnValidationRequested -= OnValidationRequested;
            CurrentEditContext.OnFieldChanged -= OnFieldChanged;
        }
    }
}

關於模型上的非同步驗證屬性,請參見 ASP.NET Core 中的驗證。

Validator 元件程式碼會跑在元件執行的地方。 在互動式 WebAssembly 中,它在瀏覽器中執行,而在互動伺服器中則透過電路在伺服器上執行。

在靜態 SSR 中,驗證器元件程式碼會在表單發佈時執行於伺服器上,且不會在請求間提供即時的 .NET 欄位驗證。

來自 Interactive WebAssembly 的遠端驗證

遠端驗證會將表單資料從互動式 WebAssembly 元件傳送到伺服器端點,並將傳回的欄位錯誤新增至表單的 EditContext。 當規則需要私有伺服器資料、外部服務或其他不該在瀏覽器執行的邏輯時,它很有用。

形式:

  1. 在本地執行資料註解驗證。
  2. 從端點傳送本地有效的輸入 OnValidSubmit。
  3. 接收來自伺服器、以欄位為鍵的驗證錯誤。
  4. 透過驗證器元件在表單中新增遠端錯誤。

OnValidSubmit 只代表本機驗證成功。 遠端驗證成功後,處理或儲存模型。

Important

不要把私人驗證資料或商業規則傳送給瀏覽器。 伺服器必須獨立驗證每個請求,因為客戶端驗證可能會被繞過。

此範例在表格提交時遠端驗證。 對於即時的每場遠端檢查,請使用 「新增非同步驗證」中的非同步欄位驗證模式。

若 WebAssembly 表單為預先渲染,其用戶端服務也必須在預渲染期間可用。 關於可用方法,請參見預渲染 ASP.NET Core Razor 元件。

用最小 API 驗證

在處理常式執行之前,於伺服器專案中呼叫 AddValidation,以驗證支援的端點參數。

用於產生驗證元資料的 Microsoft.Extensions.Validation API 在 .NET 10 中屬於實驗性質。 詳情請參見 ASP.NET Core 中的驗證。

如果模型是在 .Client 專案中宣告的,請依照 Validation in ASP.NET Core 中的說明,在這兩個專案中註冊為其產生的驗證中繼資料。

端點會新增一個私有商業規則,並回傳依模型成員名稱鍵入的錯誤:

app.MapPost("/api/starships/validate", (StarshipModel model) =>
{
    Dictionary<string, string[]> errors = [];

    if (model.Classification == "Defense" &&
        string.IsNullOrWhiteSpace(model.Description))
    {
        errors[nameof(model.Description)] =
            ["A defense ship requires a description."];
    }

    if (errors.Count > 0)
    {
        return Results.ValidationProblem(errors);
    }

    return Results.NoContent();
});
app.MapPost("/api/starships/validate", (StarshipModel model) =>
{
    Dictionary<string, string[]> errors = [];

    if (model.Classification == "Defense" &&
        string.IsNullOrWhiteSpace(model.Description))
    {
        errors[nameof(model.Description)] =
            ["A defense ship requires a description."];
    }

    if (errors.Count > 0)
    {
        return Results.ValidationProblem(errors);
    }

    return Results.NoContent();
});

自動驗證會在處理器執行前拒絕無效的資料註解。 ValidationProblem 會回傳 400 Bad Request,其中包含具有欄位鍵控訊息的 errors 屬性。 成功驗證後返回 204 No Content。

用 API 控制器驗證

在託管 Blazor WebAssembly 解決方案中,將共享模型放入專案中 Shared ,並用專案中的 Server API 控制器驗證。 屬性 [ApiController] 會在動作執行前自動拒絕無效的資料註解。

[ApiController]
[Route("api/starships/validate")]
public class StarshipValidationController : ControllerBase
{
    [HttpPost]
    public IActionResult Validate(StarshipModel model)
    {
        if (model.Classification == "Defense" &&
            string.IsNullOrWhiteSpace(model.Description))
        {
            ModelState.AddModelError(
                nameof(model.Description),
                "A defense ship requires a description.");
        }

        if (!ModelState.IsValid)
        {
            return ValidationProblem(ModelState);
        }

        return NoContent();
    }
}

在伺服器專案中註冊並映射控制器。 當驗證失敗時,控制器會以 400 Bad Request 回應傳回 204 No Content;成功時則傳回 ValidationProblemDetails。

呼叫端點並顯示錯誤

在 WebAssembly 專案中使用應用程式的基底位址註冊 HttpClient:

builder.Services.AddScoped(sp =>
    new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped(sp =>
    new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

將 CustomValidation 中的 元件放入表單中:

@page "/"
@using System.Net
@using System.Net.Http.Json
@using BlazorWebAppRemoteValidation.Client.Models
@inject HttpClient Http

<PageTitle>Remote validation</PageTitle>

<h1>Remote validation</h1>

<p>Local validation runs before the form calls the remote endpoint. The endpoint validates the model again and applies a private business rule that requires a description for defense ships.</p>

<EditForm Model="Model" OnValidSubmit="Submit">
    <DataAnnotationsValidator />
    <CustomValidation @ref="remoteErrors" />
    <ValidationSummary />

    <p>
        <label>
            Identifier:
            <InputText id="identifier" @bind-Value="Model.Identifier" />
        </label>
        <ValidationMessage For="() => Model.Identifier" />
    </p>

    <p>
        <label>
            Classification:
            <InputSelect id="classification" @bind-Value="Model.Classification">
                <option value="">Select...</option>
                <option value="Exploration">Exploration</option>
                <option value="Defense">Defense</option>
            </InputSelect>
        </label>
        <ValidationMessage For="() => Model.Classification" />
    </p>

    <p>
        <label>
            Description:
            <InputText id="description" @bind-Value="Model.Description" />
        </label>
        <ValidationMessage For="() => Model.Description" />
    </p>

    <button id="submit" type="submit">Submit</button>
</EditForm>

@if (accepted)
{
    <p id="accepted" role="status">The server accepted the form.</p>
}

@code {
    private StarshipModel Model { get; } = new();
    private CustomValidation? remoteErrors;
    private bool accepted;

    private async Task Submit()
    {
        accepted = false;

        using var response = await Http.PostAsJsonAsync(
            "api/starships/validate", Model);

        if (response.IsSuccessStatusCode)
        {
            accepted = true;
            return;
        }

        if (response.StatusCode == HttpStatusCode.BadRequest)
        {
            var problem = await response.Content
                .ReadFromJsonAsync<ValidationProblemResponse>()
                ?? throw new InvalidOperationException(
                    "The validation response didn't contain a response body.");

            remoteErrors!.DisplayErrors(problem.Errors);
            return;
        }

        response.EnsureSuccessStatusCode();
    }

    private sealed record ValidationProblemResponse(
        Dictionary<string, string[]> Errors);
}
@using System.Net
@using System.Net.Http.Json
@inject HttpClient Http

<EditForm Model="Model" OnValidSubmit="Submit">
    <DataAnnotationsValidator />
    <CustomValidation @ref="remoteErrors" />
    <ValidationSummary />

    ...
</EditForm>

@code {
    private StarshipModel Model { get; } = new StarshipModel();
    private CustomValidation? remoteErrors;

    private async Task Submit()
    {
        using var response = await Http.PostAsJsonAsync(
            "api/starships/validate", Model);

        if (response.IsSuccessStatusCode)
        {
            // Process or save the model.
            return;
        }

        if (response.StatusCode == HttpStatusCode.BadRequest)
        {
            var problem = await response.Content
                .ReadFromJsonAsync<ValidationProblemResponse>();

            if (problem is not null)
            {
                remoteErrors!.DisplayErrors(problem.Errors);
            }

            return;
        }

        response.EnsureSuccessStatusCode();
    }

    private sealed class ValidationProblemResponse
    {
        public Dictionary<string, string[]> Errors { get; set; } =
            new Dictionary<string, string[]>();
    }
}

驗證元件會在遠端欄位變更時清除該欄位錯誤,讓使用者能修正該值並再次提交。 根據應用程式的安全需求保護端點;認證與授權不在本驗證範例的範圍內。

完整的遠端驗證範例包括主機端點、共享模型、跨組語言驗證註冊、驗證器元件及互動式 WebAssembly 表單。

.NET 10 遠端驗證範例展示了互動式自動應用程式中相同的驗證流程,並具備認證與伺服器端代理。

最小 API 快速參考