asp.net-mvc - FluentValidation 将参数传递给 WithMessage

标签 asp.net-mvc fluentvalidation

我在验证器中有以下代码:

RuleFor(mb => mb.Amount).
Must((mb, amount) =>
                {
                   var betLimit = _battlesService.GetBetLimit(mb.BattleId);

                   mb.Amount <= betLimit;
                }).
WithMessage("Bet should be less than {0}", "bet limit value should be placed here");

有没有办法将 betLimit 值传递给 WithMessage 方法?我看到的唯一解决方案是将 betLimit 值设置为 ViewModel 的某些属性,然后使用 funcs 在 WithMessage 重载中访问它。但它很丑。

最佳答案

Amount不用于获取betLimit ,当你的验证器启动时,你不能把下注限制拉到一个字段中,并在任何你想要的地方使用它吗?就像是:

public ViewModelValidator(IBattlesService battlesService)
{
    var betLimit = battlesService.GetBetLimit();

    RuleFor(mb => mb.Amount).
    Must((mb, amount) =>
                    {
                       mb.Amount <= betLimit;
                    }).
    WithMessage(string.Format("Bet should be less than {0}", "bet limit value should be placed here", betLimit));
    ...
}

更新:

我现在看到您从 View 模型中添加了参数。基于 FluentValidation 文档 here 中的第三个示例,您似乎应该能够像这样获得它:
    public ViewModelValidator(IBattlesService battlesService)
    {
        RuleFor(mb => mb.Amount).
        Must((mb, amount) =>
                        {
                           mb.Amount <= betLimit;
                        }).
        WithMessage("Bet should be less than {0}", mb => battlesService.GetBetLimit(mb.BattleId));
        ...
    }

关于asp.net-mvc - FluentValidation 将参数传递给 WithMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7436183/

相关文章:

asp.net-mvc - AuthorizeAttribute构造函数参数Roles equals string.empty是什么意思?

c# - 带有 mvvmlight 和 Fluent.Validation 的 WPF MVVM

c# - 来自 App 常量的流畅验证自定义检查

asp.net-mvc-3 - FluentValidation-跨多个属性进行验证

c# - 流畅的验证规则

asp.net-mvc - 请推荐为 MVC 网格实现内联编辑的方法?

asp.net-mvc - 获取 `kendo.all.min.js` 的 kendo telerik 源 map 时出现 404 错误

c# - 在 ASP.Net MVC 中集中正则表达式验证模式

c# - 如何将单元测试添加到我的流利验证类中?