Search code examples
c#.net-coreblazorfluentvalidation

Validate List of model with one Editform in Blazor with Blazored.fluentValidator


I have a Editform warping a List, I want to validate each field for each model.

Iam using Fluentvalidator and Blazor.

The use case: So the logic is when I click on handlesubmit all the models in my List needs to be validated with fluentvalidator. What I don't understand is how I can make a editform that will validate all the models with one submit, the Editform Model only points to one specific model but not the ones in the List

Here is my 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>`

Here is my startup.cs: services.AddTransient<IValidator<Model>, ModelValidator>();

And here is my 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);
        }
    }

Solution

  • Add a validator for your outer model that contains the list and then use RuleForEach to validate each inner model:

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