Blazor Server表单验证失效问题排查求助
问题排查与解决方案
核心问题:字段而非属性导致验证失效
你的Form类中定义的是字段(field)而非属性(property),Blazor的DataAnnotations验证仅对带有get和set访问器的属性生效。数据注解验证机制需要通过属性的访问器拦截并执行验证逻辑,直接使用字段会绕过这一机制,导致验证完全不生效,同时表单会直接触发提交事件。
修复步骤
1. 将Form类的字段改为属性
修改Form类,把需要验证的字段替换为带get; set;的属性(同时初始化避免空引用):
using System.ComponentModel.DataAnnotations; namespace WebLab.Pages._9; public class Form { [Required(AllowEmptyStrings = false)] [StringLength(50, ErrorMessage = "Name too long")] public string Name { get; set; } = string.Empty; [Required] [MinLength(2)] public string City { get; set; } = string.Empty; public string Address { get; set; } = string.Empty; public DateTime? Birthday { get; set; } // 修正类型适配InputDate组件 public string Mail { get; set; } = string.Empty; }
2. 修正InputDate的绑定类型
原代码中Birthday是string类型,但InputDate组件要求绑定DateTime或DateTime?类型,类型不匹配会导致隐性错误,间接影响验证逻辑执行。改用DateTime?(可空类型,允许用户不填写)适配组件要求。
3. 页面代码对应调整(无需修改绑定语法)
页面中InputDate的绑定代码无需改动,已适配修正后的属性类型:
<div> <label>Birthdate</label> <InputDate @bind-Value="@form.Birthday" class="form-control"></InputDate> </div>
验证效果验证
修改完成后,提交空的Name或长度不足2的City时,ValidationSummary会显示对应错误信息,表单会阻止提交,直到所有验证规则通过。
内容的提问来源于stack exchange,提问作者SelfishCrawler
相关产品推荐
相关产品推荐

