我在验证器中有以下代码:
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 的某些属性,然后在WithMessage 重载中使用funcs 访问它。但它很丑。
由于
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));
...
}
更新:
我现在看到您从视图模型添加了参数。 根据 FluentValidation 文档中的第三个示例,您应该能够像这样访问它:
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));
...
}
RuleFor(mb => mb.Amount).
Must((mb, amount, context) =>
{
var betLimit = _battlesService.GetBetLimit(mb.BattleId);
context.MessageFormatter.AppendArgument("BetLimit", betLimit );
mb.Amount <= betLimit;
}).
WithMessage("Bet should be less than {BetLimit}");