流利的验证自定义检查

时间:2019-03-08 01:59:08

标签: c# fluentvalidation

使用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验证库为该检查创建自定义方法?

1 个答案:

答案 0 :(得分:2)

您应该使用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."));