简体   繁体   English

让 FluentValidation 调用具有多个参数的函数

[英]Have FluentValidation call a function with multiple parameters

I am using FluentValidation for the server side validation.我正在使用 FluentValidation 进行服务器端验证。 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.现在,这是可行的,因为validateProfile 采用的唯一参数是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.现在,我不确定如何将 IsValid 绑定到 fluentValidation。 Any ideas?有任何想法吗?

Where is promocode coming from?促销代码从何而来? The Must method has overloads accepting Func<TProp,bool> , Func<T,TProp,bool> , and Func<T,TProp, PropertyValidatorContext, bool> Must 方法具有接受Func<TProp,bool>Func<T,TProp,bool>Func<T,TProp, PropertyValidatorContext, bool>

If promocode is a property of the object being validated, it would be easy to pass something like如果 promocode 是被验证对象的属性,则很容易传递类似

 .RuleFor(x => x.UserProfile).Must( (o, userProfile) => { return IsValid(o.promoCode, userProfile); })
//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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM