Steve
Steve

Reputation: 4563

Fluent validation custom checking

using Fluent Validation C# library I have this code which current check the balance amount when user create new bank account.

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.");


    }

}

But, now I have added an enum for AccountType: SavingAccount and CurrentAccount. Rules is Saving account needs minimum $100.00 while current account needs minimum $300.00. How should I create a custom method for this checking using Fluent Validation library?

Upvotes: 0

Views: 250

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38860

You should use the When method:

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."));

Upvotes: 2

Related Questions