当前位置:首页 > C# > 正文

Blazor表单验证完全指南(手把手教你实现自定义验证规则)

在现代Web开发中,Blazor表单验证是确保用户输入数据合法性和完整性的关键环节。本文将带你从零开始,深入浅出地掌握如何在Blazor应用中实现自定义验证规则,即使是编程新手也能轻松上手!

Blazor表单验证完全指南(手把手教你实现自定义验证规则) Blazor表单验证 自定义验证规则 Blazor WebAssembly ASP.NET Core 第1张

为什么需要自定义验证?

虽然Blazor内置了如[Required][StringLength]等常用验证属性,但在实际项目中,我们常常需要更复杂的业务逻辑验证,比如:

  • 密码强度校验
  • 邮箱格式特殊要求
  • 两个字段必须一致(如确认密码)
  • 根据其他字段动态验证

这时,我们就需要用到自定义验证规则

方法一:继承ValidationAttribute(推荐)

这是最标准、可复用性最高的方式。下面以“确认密码”为例:

using System.ComponentModel.DataAnnotations;public class CompareAttribute : ValidationAttribute{    private readonly string _otherProperty;    public CompareAttribute(string otherProperty)    {        _otherProperty = otherProperty;    }    protected override ValidationResult IsValid(        object value,         ValidationContext validationContext)    {        var otherProperty = validationContext.ObjectType            .GetProperty(_otherProperty);                if (otherProperty == null)            return new ValidationResult($"未知属性: {_otherProperty}");        var otherValue = otherProperty.GetValue(validationContext.ObjectInstance);        if (value?.ToString() != otherValue?.ToString())            return new ValidationResult(ErrorMessage ?? "两次输入不一致。");        return ValidationResult.Success;    }}

然后在你的模型类中使用它:

public class RegisterModel{    [Required(ErrorMessage = "请输入密码")]    public string Password { get; set; }    [Compare("Password", ErrorMessage = "确认密码与密码不一致")]    public string ConfirmPassword { get; set; }}

方法二:在Blazor组件中手动验证

如果你不想创建独立的验证类,也可以直接在Razor组件中处理验证逻辑:

@page "/custom-validation"@using System.ComponentModel.DataAnnotations<EditForm Model="@model" OnValidSubmit="HandleValidSubmit">    <DataAnnotationsValidator />    <ValidationSummary />    <div>        <InputText @bind-Value="model.Email" />        <ValidationMessage For="() => model.Email" />    </div>    <button type="submit">提交</button></EditForm>@code {    private UserModel model = new();    private void HandleValidSubmit()    {        // 自定义额外验证        if (!IsValidEmailDomain(model.Email))        {            // 可通过添加到ValidationMessage显示错误            // 或使用CustomValidation组件(见下文)        }    }    private bool IsValidEmailDomain(string email)    {        return email?.EndsWith("@company.com") == true;    }    public class UserModel    {        [Required]        [EmailAddress]        public string Email { get; set; }    }}

高级技巧:使用CustomValidation组件

Blazor还提供了一个强大的<CustomValidation>组件,允许你在运行时动态添加错误信息:

// CustomValidation.razor@using Microsoft.AspNetCore.Components.Forms@code {    [CascadingParameter] private EditContext CurrentEditContext { get; set; }    private ValidationMessageStore messageStore;    protected override void OnInitialized()    {        if (CurrentEditContext == null)            throw new InvalidOperationException(                $"{nameof(CustomValidation)} requires a cascading " +                $"parameter of type {nameof(EditContext)}.");        messageStore = new(CurrentEditContext);    }    public void DisplayErrors(Dictionary<string, List<string>> errors)    {        foreach (var kv in errors)        {            messageStore.ClearErrors(CurrentEditContext.Field(kv.Key));            messageStore.Add(CurrentEditContext.Field(kv.Key), kv.Value);        }        CurrentEditContext.NotifyFieldChanged(CurrentEditContext.Field(""));    }    public void ClearErrors()    {        messageStore?.Clear();        CurrentEditContext?.NotifyValidationStateChanged();    }}

在表单中使用:

<EditForm Model="@user" OnValidSubmit="SubmitForm">    <DataAnnotationsValidator />    <CustomValidation @ref="customValidation" />    <InputText @bind-Value="user.Username" />    <ValidationMessage For="() => user.Username" />    <button type="submit">注册</button></EditForm>@code {    private CustomValidation customValidation;    private User user = new();    private async Task SubmitForm()    {        // 调用API检查用户名是否已存在        var isTaken = await UserService.IsUsernameTaken(user.Username);        if (isTaken)        {            customValidation.DisplayErrors(new Dictionary<string, List<string>>            {                { nameof(user.Username), new() { "该用户名已被占用" } }            });            return;        }        // 继续注册流程...    }}

总结

通过以上三种方式,你已经掌握了在Blazor WebAssemblyASP.NET Core Blazor Server应用中实现灵活、强大的表单验证的能力。记住:

  • 简单规则 → 使用内置ValidationAttribute
  • 复杂业务逻辑 → 继承ValidationAttribute创建自定义验证
  • 动态/异步验证(如查重)→ 使用CustomValidation组件

合理运用这些技术,不仅能提升用户体验,还能有效防止无效数据进入你的系统。赶快在你的项目中试试吧!

关键词提示:本文覆盖了Blazor表单验证、自定义验证规则、Blazor WebAssembly和ASP.NET Core Blazor等核心技术点。