【问题标题】:FluentValidation Must rule affected by When condition that follows another Must ruleFluentValidation Must 规则受遵循另一个 Must 规则的 When 条件影响
【发布时间】:2016-06-23 17:55:44
【问题描述】:

我有这个流畅的验证规则:

    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 条必须规则。前 2 个与 When 条件相关。 我遇到的问题是,第二个 When 条件会影响第一个 Must 规则。例如,如果tvm.Task.Instructed 为假,输入的Deadline2016-06-22(并考虑到当前日期为2016-06-23),我希望收到Deadline can't be earlier than today 消息。但我没有收到该消息,因为第二个When 检查tvm.Task.Instructed 是否为真并返回假。所以看起来当条件不仅影响它遵循的规则。我真的很想用一行流利地写这些规则。这是可能的吗,或者除了单独定义它们之外我别无选择。

【问题讨论】:

    标签: asp.net-mvc conditional-statements fluentvalidation


    【解决方案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

    所以这应该没问题(用一些样本数据测试)

    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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2022-01-28
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2012-10-01
      相关资源
      最近更新 更多