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

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

假设我有以下视图模型:

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

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

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

   }
}

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

您必须使用谓词验证器 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
   }
}