首页 > 解决方案 > 如何在 Fluent Validation 中为 Multiple RuleFor 设置单个消息

问题描述

我是流利验证的新手。我有 4 个 if 条件,其中只有一个会执行,我想对这些条件使用 RuleFor。如果条件失败,则应显示错误代码和消息。对于我的 4 个条件,只有一个错误代码和错误消息。

如何在 RuleFor() 中使用 4 个条件以及单个 ErrorCode() 和 WithMessage()

标签: c#.net.net-corefluentvalidation

解决方案


WithErrorCode() 和 WithMessage() 接受字符串,因此您只需使用适用的详细信息设置简单的字符串变量并传递变量。

string myerror = "666";
string mymessage = "My Custom message";

RuleFor(person => myclass.Property1).NotNull().WithErrorCode(myerror).WithMessage(mymessage);        

RuleFor(person => myclass.Property2).NotNull().WithErrorCode(myerror).WithMessage(mymessage);        

RuleFor(person => myclass.Property3).NotNull().WithErrorCode(myerror).WithMessage(mymessage);        

RuleFor(person => myclass.Property4).NotNull().WithErrorCode(myerror).WithMessage(mymessage);   

您应该考虑这是否有意义,但是验证的目的是增强对数据问题的调试,因此消息和错误代码应尽可能具体。在您的情况下这可能没问题,只有您可以判断。

编辑:在下面回答您的问题。

Fluent Validation 提供了另外两种可能有用的方法。

我认为依赖项更多的是您正在寻找的。那么你可以有这样的东西;

    RuleFor(person => myclass.Property1).NotNull().DependentRules(() => {
        RuleFor(person => myclass.Property2).NotNull().WithErrorCode(myerror).WithMessage(mymessage);    
        RuleFor(person => myclass.Property3).NotNull().WithErrorCode(myerror).WithMessage(mymessage);    
        RuleFor(person => myclass.Property4).NotNull().WithErrorCode(myerror).WithMessage(mymessage);    
}).WithErrorCode(myerror).WithMessage(mymessage);
    

并且您可以在规则中嵌入规则,使用规则等。但这很快就会变得难以阅读并且难以调试。


推荐阅读