Search code examples
c#asp.net-corefluentvalidation

fluent validation - How to loop through List<string>


This is my xml :

  <recordset>
  <!-- multiple value record-->
  <record>
    <KeyName>aliases</KeyName>
    <KeyValue>
      
      <val>VENKAT</val>
      <val>vraja</val>
    </KeyValue>
  </record>


  <!-- single value record-->
  <record>
    <KeyName>accountType</KeyName>
    <KeyValue>

      <val>ADM</val>
    </KeyValue>
  </record>
</recordset>

this is my equivalent C# class for the XML.

public class Record
{
    public string KeyName { get; set; }
    public KeyValue KeyValue { get; set; }
}

public class Recordset
{
    public List<Record> Record { get; set; }
}

Now using fluent validation I am trying to validate every record in my record set.

SchemaValidator.cs

public class SchemaValidator : AbstractValidator<Entity.EigenData.Recordset>
{
    public SchemaValidator()
    {
        RuleFor(rec => rec.Record[0]).NotNull().SetValidator(new RecordValidator());
    }
}

RecordValidator.cs

public class RecordValidator : AbstractValidator<Entity.EigenData.Record>
{
    public RecordValidator()
    {
        RuleFor(rec => rec.KeyName).NotNull();
        RuleFor(rec => rec.KeyValue).NotNull();
    }
}

note :I am able to validate only first record

ie., RuleFor(rec => rec.Record[0]).NotNull().SetValidator(new RecordValidator());

How will I validate for all records in the recordset?

I tried

RuleFor(rec => rec.Record).NotNull().SetValidator(new RecordValidator()); but got conversion error

Program.cs

 //Note: Recordset contains many List<record>
 private static void Validate(Entity.EigenData.Recordset recordset)
 {
     SchemaValidator validator = new SchemaValidator();

     ValidationResult results = validator.Validate(recordset);

     if (!results.IsValid)
     {
         foreach (var failure in results.Errors)
         {
             Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
         }
     }
     // throw new NotImplementedException();
 }

Solution

  • You can count it using RuleForEach

    public class SchemaValidator : AbstractValidator<Entity.EigenData.Recordset>
    {
        public SchemaValidator()
        {   
            RuleForEach(rec => rec.Record).NotNull().SetValidator(new RecordValidator());
        }
    }