Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 784
Mikayil Abdullayev Avatar asked May 29 '15 05:05

Mikayil Abdullayev


1 Answers

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
           .WithMessagee("At least one of {0} documents should be selected",
               (model, coll) => coll.Count); // error message can use validated collection as well as source model
   }
}
like image 131
Evgeny Levin Avatar answered Nov 16 '22 23:11

Evgeny Levin