我有一个Blazor组件,里面有一个人的名字和地址。我已经把地址分开了,这样我就可以重新使用它了。我正在使用双向数据绑定的人和地址,以确保数据被传递到地址和人可以接收地址更改。
不过,我无法获得有效的证明。个人全名和地址行1不能为空。当我使用VaidationSummary时,它正确地报告两个字段都不能是空的。但是,当我使用ValidationMessage时,只有person全名报告一条验证消息。我使用的是Fluent验证,但我相信问题是ValidationMessage在复杂类型时不报告。
我认为这是因为地址第1行ValidationMessage的For()属性与主表单(Person)数据模型中的字段名不匹配。主数据模型以address类作为地址,而Address组件将其作为值。但是,如果我要重用组件,那么这种情况可能会发生!
分离像地址这样的组件似乎是一件合理的事情,而且您可能在一个表单上有多个address对象(例如,传递和计费),所以我只需要知道如何做到这一点。
有人做过这个吗?对于()实现来说,自定义ValidationMessage是必需的还是不同的?
谢谢你在这方面的帮助。这是消息来源。
表格:
<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");
}
}
发布于 2021-07-08 13:18:20
问题是,用于验证组件的ValidationContext
是组件的Value
属性,而不是父页面使用的模型。
我很难找到一些东西来让组件验证工作,直到我使用了另一个应用于组件的Value
属性的验证属性才发现了一些问题。在验证Value
时,我使用组件的EditContext
,它是通过级联参数设置的属性。我可以通过反射获得属性的名称,这意味着我可以获得正确的FieldIdentifier
,通知字段已经更改,然后从父的EditContext
获得ValidationResult
s。然后,我可以返回相同的错误详细信息。
验证属性
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;
}
}
}
}
组件
@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;
}
}
https://stackoverflow.com/questions/68180633
复制相似问题