验证 Blazor 子组件?

5
我有一个Blazor组件,包含一个人的姓名和地址。我将地址拆分出来以便复用。我正在使用双向数据绑定来确保数据被传递到地址,并且人员可以接收地址更改。但是,我无法使验证起作用。人的全名和地址行 1 不能为空。当我使用ValidationSummary时,它正确地报告两个字段都不能为空。但是当我使用ValidationMessage时,只有人的全名报告了验证消息。我正在使用Fluent验证,但我认为问题是ValidationMessage不在一个复杂类型中时不能正确报告。
我认为这是因为Address line 1的For()属性与主表单(Person)数据模型中的字段名称不匹配。主数据模型将地址类命名为Address,但是地址组件将其命名为Value。但是,如果我要重用该组件,则可能会发生这种情况!
像地址这样分离组件似乎是合理的事情,而且您可能需要在一个表单上拥有多个地址对象(例如交付和账单),因此我只需要知道如何做到这一点。
有人做过这个吗?是否需要自定义ValidationMessage或不同的For()实现?
感谢您对此的帮助。以下是源代码。
表单:
<EditForm Model=@FormData>
    <FluentValidator/>
    <ValidationSummary/>
    <InputText @bind-Value=FormData.FullName />
    <ValidationMessage For="@(() => FormData.FullName)"/>
    <ComponentAddress @bind-Value=FormData.Address />
    <input type="submit" value="Submit" class="btn btn-primary" />
</EditForm>

@code{
    PersonDataModel FormData = new PersonDataModel();
}

地址组件:

<InputText @bind-Value=Value.Address1 @onchange="UpdateValue" />
<ValidationMessage For="@(() => Value.Address1)" />
@code{
    [Parameter] public AddressDataModel Value { get; set; }
    [Parameter] public EventCallback<AddressDataModel> ValueChanged { get; set; }

    protected async Task UpdateValue()
    {
        await ValueChanged.InvokeAsync(Value);
    }
}

人员模型:

   public class PersonDataModel
    {
        [Required]
        public string FullName { get; set; }
        public AddressDataModel Address { get; set; }

        public PersonDataModel()
        {
            Address = new AddressDataModel();
        }
    }

地址模型:

public class AddressDataModel
{
    [Required]
    public string Address1 { get; set; }
}

人员流畅性验证器:

public class PersonValidator : AbstractValidator<PersonDataModel>
{
    public PersonValidator()
    {
        RuleFor(r => r.FullName).NotEmpty().WithMessage("You must enter a name");
        RuleFor(r => r.Address.Address1).NotEmpty().WithMessage("You must enter Address line 1");
    }
}

你可以查看这个链接 - Jerry Cai
所以我发现了一个关于这个的新问题。问题似乎是FieldIdentifier由字段名称定义。在子组件中,这是本地名称,但对于父表单来说,它将是ChildComponentName.FieldName。验证针对本地字段正确执行。ValidationSummary有效,因为它获取所有验证错误。ValidationMessage不起作用,因为它寻找EditContext的字段名称。由于EditContext设置为父级,名称不同,因此找不到任何消息。 - user3807918
1个回答

1
问题在于用于验证组件的ValidationContext是组件的Value属性,而不是父页面所使用的模型。
我曾经苦苦尝试让组件验证起作用,直到我想到了一种方法,即使用另一个应用于组件Value属性的验证属性。在验证Value时,我使用组件的EditContext,这是通过级联参数设置的属性。我可以通过反射获取属性的名称,这意味着我可以获取正确的FieldIdentifier,通知字段已更改,然后从父级的EditContext获取ValidationResult。然后我可以返回相同的错误详细信息。
验证属性
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using ValueBinding.Shared;

namespace ValueBinding.Data.Annotations
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class MyValidationContextCheckAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            EditContext ec = null;
            string propName = "NOT SET";

            // My StringWrapper is basic component with manual Value binding
            if (validationContext.ObjectInstance is MyStringWrapper)
            {
                var strComp = (MyStringWrapper)validationContext.ObjectInstance;
                ec = strComp.ParentEditContext; // Uses Cascading Value/Property
                propName = strComp.GetPropertyName();
            }

            if (ec != null)
            {
                FieldIdentifier fld = ec.Field(propName);
                ec.NotifyFieldChanged(in fld);

                // Validation handled in Validation Context of the correct field not the "Value" Property on component
                var errors = ec.GetValidationMessages(fld);

                if (errors.Any())
                {
                    string errorMessage = errors.First();
                    return new ValidationResult(errorMessage, new List<string> { propName });
                }
                else
                {
                    return null;
                }
            }
            else if (typeof(ComponentBase).IsAssignableFrom(validationContext.ObjectType))
            {
                return new ValidationResult($"{validationContext.MemberName} - Validation Context is Component and not data class", new List<string> { validationContext.MemberName });
            }
            else
            {
                return null;
            }
        }
    }
}

Component

@using System.Linq.Expressions
@using System.Reflection
@using Data
@using Data.Annotations

<div class="fld" style="border-color: blue;">
    <h3>@GetPropertyName()</h3>
    <InputText @bind-Value=@Value />
    <ValidationMessage For=@ValidationProperty />
    <div class="fld-info">@HelpText</div>
</div>

@code {
    [Parameter]
    public string Label { get; set; } = "NOT SET";

    [Parameter]
    public string HelpText { get; set; } = "NOT SET";

    [Parameter]
    public Expression<Func<string>> ValidationProperty { get; set; }

    private string stringValue = "NOT SET";
    [MyValidationContextCheck]
    [Parameter]
    public string Value
    {
        get => stringValue;
        set
        {
            if (!stringValue.Equals(value))
            {
                stringValue = value;
                _ = ValueChanged.InvokeAsync(stringValue);
            }
        }
    }

    [Parameter]
    public EventCallback<string> ValueChanged { get; set; }

    [CascadingParameter]
    public EditContext ParentEditContext { get; set; }

    public string GetPropertyName()
    {
        Expression body = ValidationProperty.Body;
        MemberExpression memberExpression = body as MemberExpression;
        if (memberExpression == null)
        {
            memberExpression = (MemberExpression)((UnaryExpression)body).Operand;
        }
        PropertyInfo propInfo = memberExpression.Member as PropertyInfo;
        return propInfo.Name;
    }
} 

这个结构应用于我们的基本表单输入组件,以便所有继承的组件都以相同的方式运作,这样您就不必在所有表单输入组件上应用属性。实际上,我们只有一个属性表达式参数,以便通过反射和Linq处理所有值和所有显示值,并且页面标记代码非常干净。 - AnteUp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接