当我针对单个类构建编辑表单时,一切都按预期工作。当我离开场地时,红色/绿色指示器就会出现。然而,当我将其作为一个集合时,当我离开该字段时,我会丢失红色/绿色逻辑。现在,当验证确实失败时,它总是变成绿色。当我手动调用时
_fluentValidationValidator.Validate(opt => opt.IncludeAllRuleSets())
它会相应地验证并更改字段轮廓。
处理集合时离开字段时如何正确运行验证?
<EditForm Model="Form">
<FluentValidationValidator @ref="_fluentValidationValidator" />
@foreach (var item in Form.Items)
{
<div class="row">
<div class="col-6 col-md-3 mb-1">
<label class="input-label">Name</label>
<InputText @bind-Value="item.Name"
Style="width:100%;" />
<ValidationMessage For="() => item.Name" />
</div>
</div>
}
</EditForm>
public class TestForm
{
public List<TestItem> Items { get; set; } = new();
}
public class TestFormValidator : AbstractValidator<TestForm>
{
public TestFormValidator()
{
RuleForEach(r => r.Items).SetValidator(new TestItemValidator());
}
}
public class TestItem
{
public string Name { get; set; }
}
public class TestItemValidator : AbstractValidator<TestItem>
{
public TestItemValidator()
{
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required")
.MaximumLength(6).WithMessage("Name should be at most 6 characters");
}
}
如果您通过 DI 使用验证器并且不创建任何本地实现或实例,它就可以工作。
public class TravelersDto
{
public List<TravelerDto> Travelers { get; set; } = new();
}
public class TravelersDtoValidator : AbstractValidator<TravelersDto>
{
public TravelersDtoValidator()
{
RuleForEach(x => x.Travelers).SetValidator(new TravelerDtoValidator());
}
}
而不是在您的表单中使用它:
@code {
private TravelersDto viewModel = new();
}
和
<EditForm Model="viewModel" OnValidSubmit="Save">
<FluentValidationValidator></FluentValidationValidator>
<ValidationSummary></ValidationSummary>