Search code examples
asp.net-mvcfluentvalidation

Fluent Validation ensuring a list has at least one item with property value of somevalue


Assume I have the following viewmodel:

public class TaskViewModel{
  public MTask Task {get;set;}
  public List<DocIdentifier> Documents {get;set;}
  .....
}

public class DocIdentifier{
  public string DocID {get;set;}
  public bool Selected {get;set;}
}

And here's the Fluent Validation validator I use:

public class TaskValidator : AbstractValidator<TaskViewModel>{
   public TaskValidator{

   }
}

How can I make sure that at least one DocIdentifier object in the list Documents has its Selected property value True?


Solution

  • You have to use predicate validator Must, in which you could specify custom condition based on LINQ extensions:

    public class TaskValidator : AbstractValidator<TaskViewModel>{
       public TaskValidator()
       {
           RuleFor(task => task.Documents)
               .Must(coll => coll.Any(item => item.Selected)) // you can secify custom condition in predicate validator
               .WithMessage("At least one of {0} documents should be selected",
                   (model, coll) => coll.Count); // error message can use validated collection as well as source model
       }
    }