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.
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));
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With