Fluent验证确保列表至少有一个属性值为somevalue的项目

Mik*_*yev 5 asp.net-mvc fluentvalidation

假设我有以下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;}
}
Run Code Online (Sandbox Code Playgroud)

这是Fluent Validation我使用的验证器:

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

   }
}
Run Code Online (Sandbox Code Playgroud)

如何确保列表中至少有一个DocIdentifier对象Documents具有其Selected属性值True

Evg*_*vin 8

您必须使用谓词验证器Must,您可以在其中根据LINQ扩展名指定自定义条件:

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
   }
}
Run Code Online (Sandbox Code Playgroud)