首页 > 解决方案 > Fluent 验证自定义检查

问题描述

使用 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

解决方案


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

推荐阅读