假设我有以下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
?
答案 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
}
}