You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WASM使用Fluent Validation跨字段校验错误如何前端展示

你当前遇到的问题是模型级(跨字段)的Fluent Validation错误默认属于全局错误,不会关联到任意单字段,而MudBlazor的输入控件仅会展示绑定字段自身的错误,所以没有对应位置渲染全局错误信息,可以按照以下两种方案调整:


方案1:将跨字段错误关联到指定字段(推荐,用户感知更强)

直接修改校验器的跨字段规则,把错误绑定到End或者Start字段上,不需要改前端代码,错误会直接展示在对应输入框下方:

// 替换原来的模型级校验规则即可
RuleFor(x => x.End)
    .Must((model, endValue) => model.Start < endValue)
    .WithMessage(localizer["Start must be less than end!"]);

方案2:添加全局错误展示区域

如果你希望所有模型级错误统一在表单固定位置展示,只需要在前端EditForm内添加<MudValidationSummary>组件,同时确保FluentValidationValidator开启了模型级错误同步:

@inject Microsoft.Extensions.Localization.IStringLocalizer<AddInvoiceParameterModal> _localizer

<EditForm Model="@AddInvoiceParameterModel" OnValidSubmit="SaveAsync">
    <!-- 新增IncludeModelLevelErrors配置,确保模型级错误被同步到EditContext -->
    <FluentValidationValidator @ref="_fluentValidationValidator" IncludeModelLevelErrors="true" />
    <MudDialog>
        <TitleContent>
              <MudText Typo="Typo.h6">
                        <MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-3 mb-n1" />
                        @_localizer["Add Parameter"]
                    </MudText>
        </TitleContent>
        <DialogContent>
            <!-- 新增全局错误展示区域,位置可以根据需求调整 -->
            <MudValidationSummary Class="mb-4" Color="Color.Error" />
            <MudGrid>
                <MudItem xs="12" md="6">
                    <MudTextField T="int" For="@(() => AddInvoiceParameterModel.Start)" @bind-Value="AddInvoiceParameterModel.Start" Label="@_localizer["Start"]" />
                </MudItem>
                <MudItem xs="12" md="6">
                    <MudTextField T="int" For="@(() => AddInvoiceParameterModel.End)" @bind-Value="AddInvoiceParameterModel.End" Label="@_localizer["End"]" />
                </MudItem>
                <MudItem xs="12" md="6">
                    <MudTextField T="string" For="@(() => AddInvoiceParameterModel.Prefix)" @bind-Value="AddInvoiceParameterModel.Prefix" Label="@_localizer["Prefix"]" />
                </MudItem>
            </MudGrid>
        </DialogContent>
        <DialogActions>
            <MudButton DisableElevation Variant="Variant.Filled" OnClick="Cancel">@_localizer["Cancel"]</MudButton>
                <MudButton DisableElevation Variant="Variant.Filled" ButtonType="ButtonType.Submit" Disabled="@(!Validated)" Color="Color.Success">@_localizer["Save"]</MudButton>
        </DialogActions>
    </MudDialog>
</EditForm>

内容的提问来源于stack exchange,提问作者Alex Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:51:02