Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation pass parameter to WithMessage

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 method? 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.

like image 435
SiberianGuy Avatar asked Sep 15 '11 19:09

SiberianGuy


1 Answers

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));
        ...
    }
like image 139
Brandon Linton Avatar answered Oct 07 '22 19:10

Brandon Linton