开发者

FluentValidation pass parameter to WithMessage

开发者 https://www.devze.com 2023-04-05 17:34 出处:网络
I have the following code in validator: RuleFor(mb => mb.Amount). Must((mb, amount) => { var betLimit = _battlesService.GetBetLimit(mb.BattleId);

I have the following code in validator:

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

Is there any way to pass betLimit value to WithMessage m开发者_开发问答ethod? The only solution I see is to set betLimit value to some property of ViewModel and then access it in WithMessage overload with funcs. But it is ugly.


Since Amount isn't used to get the betLimit, can't you pull the bet limit into a field when your validator fires up, and use it wherever you want? Something like:

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

UPDATE:

I see now that you added the param from the view model. Looks like you should be able to get to it like this, based on the third example in the FluentValidation docs 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));
        ...
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号