2016-06-23 71 views
0

我這有一口流利的驗證規則:FluentValidation必須由當跟隨另一必須條件排除規則的影響

RuleForEach(tvm => tvm.Task.Executors).Cascade(CascadeMode.StopOnFirstFailure).Must((tvm, exec) => { return exec.Deadline.HasValue ? exec.Deadline.Value.Date >= DateTime.Now.Date : true; }). 
     When(tvm=>!tvm.Task.Instructed). 
     WithMessage("Deadline can't be earlier than today"). 
     Must((tvm,exec)=>{ return exec.Deadline.HasValue ? exec.Deadline.Value.Date >= tvm.Task.InstructDate.Value.Date : true; }). 
     When(tvm=>tvm.Task.Instructed). 
     WithMessage("Deadline can't be earlier than the instructed date"). 
     Must((tvm, exec) => { return exec.InstructionId == (int)Instructions.TakeOwnership ? exec.Deadline != null : true; }). 
     WithMessage("Enter deadline"); 

正如你可以看到,有3條必須規則。前兩個綁定到When條件。 我遇到的問題是,第二個條件影響第一個必須規則。例如,如果tvm.Task.Instructed爲假,並且輸入的Deadline2016-06-22(並且考慮到當前日期爲2016-06-23),我預計會收到Deadline can't be earlier than today消息。但是我沒有收到這條消息,因爲第二次檢查是否爲tvm.Task.Instructed爲真並返回false。所以看起來條件不僅影響它遵循的規則。我真的很想在一條線上流利地寫出這些規則。這是可能的,否則我除了單獨定義它們之外別無選擇。

回答

1

那麼,默認情況下,When條件適用於所有驗證器。

請參閱When擴展方法的源代碼,您將得到一個具有此默認值的參數。

public static IRuleBuilderOptions<T, TProperty> Unless<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { 
      predicate.Guard("A predicate must be specified when calling Unless"); 
      return rule.When(x => !predicate(x), applyConditionTo); 
     } 

因此改變你的When,加入ApplyConditionTo.CurrentValidator

所以這應該是確定(有一些樣品測試DATAS)

RuleForEach(tvm => tvm.Task.Executors). 
     Cascade(CascadeMode.StopOnFirstFailure). 
     Must((tvm, exec) => { return exec.Deadline.HasValue ? exec.Deadline.Value.Date >= DateTime.Now.Date : true; }). 
     When(tvm=>!tvm.Task.Instructed, ApplyConditionTo.CurrentValidator). 
     WithMessage("Deadline can't be earlier than today"). 
     Must((tvm,exec)=>{ return exec.Deadline.HasValue ? exec.Deadline.Value.Date >= tvm.Task.InstructDate.Value.Date : true; }). 
     When(tvm=>tvm.Task.Instructed, ApplyConditionTo.CurrentValidator). 
     WithMessage("Deadline can't be earlier than the instructed date"). 
     Must((tvm, exec) => { return exec.InstructionId == (int)Instructions.TakeOwnership ? exec.Deadline != null : true; }). 
     WithMessage("Enter deadline");