【问题标题】:Have FluentValidation call a function with multiple parameters让 FluentValidation 调用具有多个参数的函数
【发布时间】:2013-06-13 21:07:21
【问题描述】:

我正在使用 FluentValidation 进行服务器端验证。现在我已经通过 Must 验证让它调用了一个函数:

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

现在,这行得通,因为 validateProfile 采用的唯一参数是 UserProfile。一切都很好。

我现在的问题是我试图让一个带有两个参数的函数验证数据。我试图用于验证的函数如下所示:

bool IsValid(string promocode, IUserProfile userProfile)

现在,我不确定如何将 IsValid 绑定到 fluentValidation。有什么想法吗?

【问题讨论】:

    标签: c# .net validation fluentvalidation


    【解决方案1】:
    //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();
        }
    

    【讨论】:

      【解决方案2】:

      促销代码来自哪里? Must 方法具有接受 Func&lt;TProp,bool&gt;Func&lt;T,TProp,bool&gt;Func&lt;T,TProp, PropertyValidatorContext, bool&gt; 的重载

      如果促销代码是正在验证的对象的属性,则很容易传递类似

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

      【讨论】:

      • 非常感谢。是的,促销代码是正在验证的对象的属性。而且我想将错误显示为促销代码错误,因此我对您发布的代码进行了细微更改。但是您发送的内容基本上效果很好。这是我更改的代码 RuleFor(x => x.PromoCode).Must((o, promocode) => IsValid(promocode, o.UserProfile));
      猜你喜欢
      • 2011-11-21
      • 1970-01-01
      • 2013-10-17
      • 2013-11-14
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多