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

Blazored.FluentValidation中IBrowserFile的ValidationMessage不生效问题求助

Blazor文件上传字段ValidationMessage不显示的解决方案

问题现状

使用Blazor 6.0 + Blazored.FluentValidation 2.1.0实现表单验证时,文本输入框的ValidationMessage能正常显示错误提示,但文件上传对应的IBrowserFile字段,只有ValidationSummary能展示错误信息,单独的ValidationMessage组件无任何输出。

问题原因

InputFile组件不支持@bind-Value双向绑定,当选择文件更新模型属性后,Blazor表单验证系统无法自动感知到File字段的变更,导致ValidationMessage组件无法同步错误状态。

解决方案

步骤1:获取EditContext并手动触发字段验证更新

在EditForm上添加引用以获取对应的EditContext,然后在文件选择事件中,更新模型后手动通知验证系统字段已变更。

步骤2:调整ValidationMessage组件

移除ValidationMessage上的FluentValidation属性,Blazored.FluentValidation会自动处理验证关联。

修改后的完整代码

@page "/fileupload"
@using Blazored.FluentValidation
@using FluentValidation
@using Microsoft.AspNetCore.Components.Forms

<EditForm @ref="editForm" Model="@model" OnValidSubmit="@HandleSubmit">
    <FluentValidationValidator />
    <ValidationSummary />
    <p>
        <label>Name: </label>
        <InputText @bind-Value="@model.Name" />
        <ValidationMessage For="@(() => model.Name)" />
    </p>
    <p>
        <label>File: </label>
        <InputFile OnChange="@OnFileSelected" />
        <ValidationMessage For="@(() => model.File)" />
    </p>
    <button type="submit">Submit</button>
</EditForm>

@code {
    private FileUploadModel model = new();
    private EditForm editForm;

    private void HandleSubmit()
    {
        // 处理提交逻辑
    }

    private void OnFileSelected(InputFileChangeEventArgs e)
    {
        model.File = e.File;
        // 手动触发File字段的验证状态更新
        var fieldIdentifier = new FieldIdentifier(model, nameof(model.File));
        editForm.EditContext.NotifyFieldChanged(fieldIdentifier);
    }

    public class FileUploadValidator : AbstractValidator<FileUploadModel>
    {
        public FileUploadValidator()
        {
            RuleFor(m => m.Name).NotEmpty().WithMessage("Name is required");
            RuleFor(m => m.File).NotNull().WithMessage("File is required");
            RuleFor(m => m.File.Size).LessThanOrEqualTo(1024 * 1024).WithMessage("File size must be less than 1 MB");
            RuleFor(m => m.File.ContentType).Must(x => x.Equals("image/jpeg") || x.Equals("image/png")).WithMessage("Only jpeg and png files are allowed");
        }
    }

    public class FileUploadModel
    {
        public string Name { get; set; }
        public IBrowserFile File { get; set; }
    }
}

额外说明

  • 手动调用NotifyFieldChanged会让验证系统重新校验File字段,确保ValidationMessage能实时获取错误状态。
  • 如果需要在页面加载时就显示文件必填的错误,可以在组件初始化时手动触发一次验证:
    protected override void OnInitialized()
      {
          base.OnInitialized();
          var fieldIdentifier = new FieldIdentifier(model, nameof(model.File));
          editForm.EditContext.NotifyFieldChanged(fieldIdentifier);
      }
    

内容的提问来源于stack exchange,提问作者Alexander Christov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:14:52