繁体   English   中英

如何在 Fluent Validation 中为 Multiple RuleFor 设置单个消息

[英]How to set single message for Multiple RuleFor in Fluent Validation

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM