Have FluentValidation call a function with multiple parameters

Lost picture Lost · Jun 17, 2013 · Viewed 11.5k times · Source

I am using FluentValidation for the server side validation. Now I have had it call a function before with Must validation:

RuleFor(x => x.UserProfile).Must(ValidateProfile).WithMessage("We are sorry, you have already logged  on " + DateTime.Now + ". Please come again tomorrow.");

Now, that works because the only parameter that validateProfile takes is UserProfile. it is all good.

My problem now is that I am trying to have a function with two parameters validate the data.The function which I am trying to use for validation looks like below:

bool IsValid(string promocode, IUserProfile userProfile)

Now, I am not sure how to bind IsValid to a fluentValidation. Any ideas?

Answer

Japple picture Japple · Jun 17, 2013

Where is promocode coming from? The Must method has overloads accepting Func<TProp,bool>, Func<T,TProp,bool>, and Func<T,TProp, PropertyValidatorContext, bool>

If promocode is a property of the object being validated, it would be easy to pass something like

 .RuleFor(x => x.UserProfile).Must( (o, userProfile) => { return IsValid(o.promoCode, userProfile); })