如何对自定义对象制作的属性使用 Blazor ValidationMessage

How to use Blazor ValidationMessage on properties made from custom objects

我们如何在验证时让 ValidationMessageFor 包含子对象?

我的 class 看起来像这样:

public class Person
{
    public Person()
    {
        Name = "";
        FavoriteGame = "";
    }

    [Required(ErrorMessage = "Person's name is required and must not be empty.")]
    public string Name { get; set; }

    public string FavoriteGame { get; set; }
}

public class Team
{
    public Team()
    {
        Name = "";
        Game = "";
        Coach = new Person();
    }

    [Required(ErrorMessage = "Team name is required and must not be empty.")]
    public string Name { get; set; }

    public string Game { get; set; }

    public Person Coach { get; set; }
}

我的 Blazor EditForm 如下所示:

<EditForm Model="@myTeam" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div class="row p-4">
        <label>Team Name:</label>
        <InputText id="name" @bind-Value="@myTeam.Name" />
        <ValidationMessage For="@(() => myTeam.Name)" />
    </div>

    <div class="row p-4">
        <label>Team Game:</label>
        <InputText id="name" @bind-Value="@myTeam.Game" />
        <ValidationMessage For="@(() => myTeam.Game)" />
    </div>

    <div class="row p-4">
        <label>Coach Name:</label>
        <InputText id="name" @bind-Value="@myTeam.Coach.Name" />
        <ValidationMessage For="@(() => myTeam.Coach.Name)" />
    </div>

    <div class="row p-4">
        <label>Coach's Favorite Game:</label>
        <InputText id="name" @bind-Value="@myTeam.Coach.FavoriteGame" />
        <ValidationMessage For="@(() => myTeam.Coach.FavoriteGame)" />
    </div>

    <div class="row p-4">
        <button type="submit" class="btn btn-success">Submit</button>
    </div>
</EditForm>

但是在运行时,只显示 class Team 中的验证... class Person 的验证被跳过,并且在运行时不会被调用或显示。

是否有一种简单的方法可以让 ValidationMessageFor 为由自定义对象组成的 class 属性工作,而无需创建全新的自定义验证器或自定义 ValidationMessageFor 组件?

请在此处查看 blazor 文档: https://docs.microsoft.com/en-gb/aspnet/core/blazor/forms-validation?view=aspnetcore-3.1#nested-models-collection-types-and-complex-types

基本上你需要在 blazor 表单中使用 ObjectGraphDataAnnotationsValidator 和 [ValidateComplexType] 属性

从@AppPack 指出的文档中学习,这些是使这项工作所需的唯一更改:

  1. 安装Microsoft.AspNetCore.Components.DataAnnotations.Validation预发布)包

  2. 在复数 属性 上使用 [ValidateComplexType]下面的代码示例

    [验证复杂类型] public 个人教练 { get;放; }

  3. 将剃须刀页面中的 DataAnnotationsValidator 替换为 ObjectGraphDataAnnotationsValidator