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

时间:2015-05-29 05:27:25

标签: 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;}
}

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

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

   }
}

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

1 个答案:

答案 0 :(得分:6)

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