在验证者级别使用CascadeMode.StopOnFirstFailure [英] Using CascadeMode.StopOnFirstFailure on a validator level

查看:222
本文介绍了在验证者级别使用CascadeMode.StopOnFirstFailure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过FluentValidation 文档我了解到可以通过设置层叠模式来中止验证

From the FluentValidation documentation I learned that I can abort validation by setting the cascade mode.

RuleFor(x => x.Surname)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull()
.NotEqual("foo");

这样,如果属性 Surname 为空,则将不执行相等性检查,并防止出现空指针异常.在文档的更深处,这暗示着这不仅在规则内,而且在验证者层上也都适用.

That way if the property Surname is null, the equality check won't be executed and a null pointer exception prevented. Further down in the documentation it is implied that this would also work not only within a rule but on a validator level as well.

public class PersonValidator : AbstractValidator<Person> {
  public PersonValidator() {

    // First set the cascade mode
    CascadeMode = CascadeMode.StopOnFirstFailure;

    // Rule definitions follow
    RuleFor(...) 
    RuleFor(...)
  }
}

我不在规则定义内设置CascadeMode,而是为验证程序的实例设置了CascadeMode.预期的行为是,如果第一个RuleFor 失败,则第二个RuleFor不会被评估,但事实并非如此.不管以前的验证错误如何,所有规则都将被评估.

I set the CascadeMode not inside the rule definition but for an instance of a validator. The expected behaviour would be that if the first RuleFor fails, the second RuleFor won't be evaluated but that's not the case. Regardless of previous validation errors, all rules are being evaluated.

我使用错了吗?还是我误解了文档?

Am I using it wrong or did I misinterpret the documentation?

推荐答案

根据JeremyS的 answer ,我有误解了CascadeMode的目的.实际上,它并不是要在验证者级别上起作用,而只是在规则内起作用.

According to the JeremyS' answer, I have misunderstood the purpose of the CascadeMode. It is in fact not intended to have effect on a validator level but only within a rule.

这篇关于在验证者级别使用CascadeMode.StopOnFirstFailure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆