我在验证器中有以下代码:
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重载中访问它。但它很难看。
答案 0 :(得分:4)
由于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));
...
}
<强>更新强>
我现在看到你从视图模型中添加了param。根据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));
...
}