SuperAPI AI 工具集

blazor-forms-validation

前端与建站

查看项目

更新于 10-16 04:40

技能介绍

用途

该技能面向 Blazor 应用中的表单构建与数据验证,提供从 EditForm 搭建、输入组件选择、模型验证到数据绑定的实践参考。适用于需要在 Blazor 中实现表单提交、字段校验、文件上传与双向绑定的开发场景。

主要能力

EditForm 与验证组件

使用 <EditForm> 承载表单,配合 OnValidSubmit 处理提交,并通过 FormName 指定表单名。在交互式渲染下可标注 @rendermode InteractiveServer。表单内使用 <DataAnnotationsValidator /> 启用基于特性的验证,<ValidationSummary /> 汇总错误,<ValidationMessage For="..." /> 显示单字段错误。

DataAnnotations 模型验证

在模型类上使用验证特性,例如:

  • [Required(ErrorMessage = "Name is required")]
  • [StringLength(200, MinimumLength = 2)]
  • [EmailAddress]
  • [Range(1, int.MaxValue, ErrorMessage = "Select a category")]
  • [Range(typeof(bool), "true", "true", ErrorMessage = "Must accept terms")]

FluentValidation 集成

通过安装 Blazored.FluentValidation 引入 FluentValidation。定义继承 AbstractValidator<T> 的验证器,使用 RuleFor、NotEmpty、MaximumLength、EmailAddress、GreaterThan 等规则,并在表单中引入 @using Blazored.FluentValidation 与 <FluentValidationValidator /> 组件。

SSR 表单处理(.NET 10)

对于静态 SSR 页面,使用 [SupplyParameterFromForm] 接收表单数据,表单需设置 method="post" 并包含 <AntiforgeryToken />。示例中通过 ItemService.CreateAsync(Model) 提交后使用 Navigation.NavigateTo("/items") 跳转。

输入组件

资料给出组件与绑定类型、HTML 的对照:

  • InputText → string → <input type="text">
  • InputTextArea → string → <textarea>
  • InputNumber<T> → int、decimal 等 → <input type="number">
  • InputDate<T> → DateTime、DateOnly → <input type="date">
  • InputCheckbox → bool → <input type="checkbox">
  • InputSelect<T> → enum、int、string → <select>
  • InputRadio<T> → enum、string → <input type="radio">
  • InputFile → IBrowserFile → <input type="file">

文件上传

使用 <InputFile OnChange="HandleFileSelected" accept=".pdf,.docx" multiple />,在回调中通过 e.GetMultipleFiles(maxAllowedFiles: 5) 获取文件,可检查 file.Size 限制大小,并使用 file.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024) 读取流。

数据绑定模式

  • 基础 @bind:默认在元素失焦时更新。
  • @bind:event:如 @bind:event="oninput" 改为每次按键更新。
  • @bind:get / @bind:set:带自定义逻辑的双向绑定。资料强调不要用 value="@x" @oninput="handler" 做双向绑定,因为 Blazor 不会把值同步回去,应始终使用 @bind:get / @bind:set。
  • @bind:after:绑定完成后执行异步逻辑,如触发搜索。
  • @bind:format:日期格式化,如 @bind:format="yyyy-MM-dd"。
  • 子组件双向绑定:父组件 <YearSelector @bind-Year="selectedYear" />,子组件使用 @bind:get="Year" 与 @bind:set="YearChanged",并遵循参数名加 Changed 后缀的约定。
  • 多选绑定:<select @bind="SelectedCities" multiple> 绑定到字符串数组。

使用方式

按资料示例,在 Razor 组件中引入相应命名空间与验证组件,定义模型与验证规则,使用 EditForm 与输入组件完成表单,并按需选择绑定模式。FluentValidation 需先安装 Blazored.FluentValidation。

适用场景

适用于 Blazor 中需要表单录入、字段校验、文件上传、SSR 表单提交以及自定义双向绑定的开发任务。

限制

资料未提供该技能的安装方式、版本兼容范围、性能表现或收费信息,暂未提供。