【问题标题】:Fluent validation custom checkingFluent 验证自定义检查
【发布时间】:2019-03-08 01:59:07
【问题描述】:

使用 Fluent Validation C# 库我有这段代码,当用户创建新的银行账户时,它会检查余额。

public class BankAccountValidator : AbstractValidator<BankAccount>
{
    private AppDbContext db = new AppDbContext();

    public BankAccountValidator()
    {

        RuleFor(x => x.Balance).GreaterThanOrEqualTo(50).WithMessage($"A minimum of $100.00 balance is required to open Saving bank account type.");


    }

}

但是,现在我为 AccountType 添加了一个枚举:SavingAccount 和 CurrentAccount。规则是储蓄账户至少需要 100.00 美元,而活期账户需要至少 300.00 美元。我应该如何使用 Fluent Validation 库为此检查创建自定义方法?

【问题讨论】:

    标签: c# fluentvalidation


    【解决方案1】:

    您应该使用When 方法:

    When(x => x.AccountType == AccountType.SavingAccount, 
        () => RuleFor(x => x.Balance)
                .GreaterThanOrEqualTo(100)
                .WithMessage($"A minimum of $100.00 balance is required to open Saving bank account type."));
    
    When(x => x.AccountType == AccountType.CurrentAccount,
        () => RuleFor(x => x.Balance)
                .GreaterThanOrEqualTo(300)
                .WithMessage($"A minimum of $300.00 balance is required to open Current bank account type."));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多