【问题标题】:Validate List of model with one Editform in Blazor with Blazored.fluentValidator使用 Blazored.fluentValidator 在 Blazor 中使用一个 Editform 验证模型列表
【发布时间】:2021-08-26 10:45:23
【问题描述】:

我有一个扭曲列表的 Editform,我想验证每个模型的每个字段。

我正在使用 Fluentvalidator 和 Blazor。

用例: 所以逻辑是当我点击handlesubmit时,我列表中的所有模型都需要使用fluentvalidator进行验证。 我不明白的是如何制作一个编辑表单,通过一次提交来验证所有模型,Editform 模型只指向一个特定的模型,而不是列表中的模型

这是我的编辑表单:

<EditForm Model="@Model" OnValidSubmit="@HandleSubmitModel">
  <FluentValidationValidator @ref="fluentValidationValidator"/>
  <div class="ModelContainer">
    @foreach (var _model in _Models)
     {
      <div class="Model-Item">
        <ModelComponent @key="_Models.IndexOf(_model)" Model="_model" 
                             Remove="RemoveModel"/>
      </div>
      } 
  </div>
</EditForm>`

这是我的 startup.cs: services.AddTransient&lt;IValidator&lt;Model&gt;, ModelValidator&gt;();

这是我的 ModelValidator.cs:

public class ModelValidator: AbstractValidator<Model>
    {
        public ModelValidator()
        {
            RuleFor(x => x.RegistrationNumber).NotEmpty();
            RuleFor(x => x.Email).NotEmpty();
            RuleFor(x => x.Capacity).GreaterThan(v => 0);
        }
    }

【问题讨论】:

    标签: c# .net-core blazor fluentvalidation


    【解决方案1】:

    为包含列表的外部模型添加一个验证器,然后使用RuleForEach 验证每个内部模型:

    public class OuterModel
    {
        public List<Model> Models { get; set; }
    }
    
    public class OuterModelValidator : AbstractValidator<OuterModel>
    {
        public OuterModelValidator()
        {
            RuleForEach(r => r.Models).SetValidator(new ModelValidator());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 2020-10-14
      • 2020-06-16
      • 2020-10-26
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      相关资源
      最近更新 更多