5

否则,我总是需要null在执行任何其他验证之前检查该值是否存在。如果我有许多正在使用的自定义检查,这有点烦人Must()

我放在NotEmpty()它的最顶部,因此它已经返回false,是否可以停在那里?

例子

RuleFor(x => x.Name)
    .NotEmpty() // Can we not even continue if this fails?
    .Length(2, 32)
    .Must(x =>
    {
        var reserved = new[] {"id", "email", "passwordhash", "passwordsalt", "description"};
        return !reserved.Contains(x.ToLowerInvariant()); // Exception, x is null
    });
4

1 回答 1

3

这里。它被称为 CascadeMode,可以像这样在单个规则上设置:

RuleFor(x => x.Name)
    .Cascade(CascadeMode.StopOnFirstFailure)
    .NotEmpty()
    .Length(2, 32);

或者可以通过以下方式全局设置:

ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;

注意:如果您在全局范围内设置它,则可以CascadeMode.Continue在任何单个验证器类或任何单个规则上覆盖它。

于 2014-07-23T00:22:48.697 回答