Home > Mobile >  fluent validation - How to loop through List<string>
fluent validation - How to loop through List<string>

Time:05-19

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();
 }

CodePudding user response:

You can count it using RuleForEach

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