【问题标题】:How to set single message for Multiple RuleFor in Fluent Validation如何在 Fluent Validation 中为 Multiple RuleFor 设置单个消息
【发布时间】:2021-04-04 07:15:52
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net .net-core fluentvalidation


    【解决方案1】:

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

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

    【讨论】:

    • 我只写过这种格式,但假设只有 1 个条件为真,其他条件应该被跳过并作为有效的输出。错误,我想要错误。那么上述方式有可能吗?
    • 您可以通过这种方式进行自定义检查,并在一个条件失败时返回 stackoverflow.com/questions/20529085/…
    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    相关资源
    最近更新 更多