Question

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?

Was it helpful?

Solution

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

OTHER TIPS

//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();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top