Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have FluentValidation call a function with multiple parameters

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?

like image 399
Lost Avatar asked Jun 17 '13 19:06

Lost


2 Answers

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); })
like image 51
Japple Avatar answered Oct 03 '22 23:10

Japple


//with MustAsync

RuleFor(v => v.UserId).MustAsync(
            async (model, userId, cancellation) =>
           {
               return await IsValid(model.PromoCode, userId, cancellation);
           }
         ).WithMessage("{PropertyName} message.");


 private async Task<bool> IsUniqueUserNameAsync(string promoCode, string userId, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
like image 22
Gurung Avatar answered Oct 03 '22 23:10

Gurung