FluentValidation规则链接在第一次失败时不会停止 [英] FluentValidation rules chaining not stopping at first failure

查看:146
本文介绍了FluentValidation规则链接在第一次失败时不会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模特:

public class DTO
{
    public int[] StatementItems { get; set; }
}

我想验证一下:

  1. StatementItems不为空
  2. StatementItems不为空
  3. StatementItems不包含任何重复的ID
  1. StatementItems is not null
  2. StatementItems is not empty
  3. StatementItems does not contain any duplicate IDs

我创建的验证规则链是:

The validation rule chain I created is:

RuleFor(x => x.StatementItems).NotNull().NotEmpty().Must(x => x.Distinct().Count() == x.Count());

我的测验是:

_validator.ShouldHaveValidationErrorFor(x => x.StatementItems, null as int[]);

当我运行传递空值的测试时,我希望它在链的第一个规则(NotNull())上失败并停在那里.但是,它抱怨Must()中使用的lamda值为空.

When I run the test passing in a null value, I would expect it to fail on the first rule of the chain (NotNull()) and stop there. However, it complains that the lamda value used in the Must() is null.

我是否认为如果NotNull()失败就不应该运行Must()是错误的吗?如果是这样,该规则应如何编写?

Am I wrong in thinking that the Must() shouldn't be run if the NotNull() fails? If so, how should this rule be written?

谢谢

推荐答案

尽管@NPras的回答确实为我提供了解决方案,但我不喜欢复制NotNull规则这一事实.在对FluentValidation进行更多研究之后,我已使用DependentRules:

Although @NPras's answer did supply my with a solution, I didn't like the fact that I'm duplicating the NotNull rule. After a bit more research on FluentValidation I have implemented it using DependentRules:

RuleFor(x => x.StatementItems).NotNull().NotEmpty()
            .DependentRules(d =>
                d.RuleFor(x => x.StatementItems).Must(x => x.Distinct().Count() == x.Count())
            );

因此,现在仅当前两个规则均有效时才触发Must条件.

So now the Must condition is only fired when the previous two rules are valid.

这篇关于FluentValidation规则链接在第一次失败时不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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