c# - 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 库为此检查创建自定义方法?
解决方案
您应该使用以下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."));
推荐阅读
- java - spring cloud config客户端立即启动和停止
- ios - Swift 5:如何读取 plist 文件中的变量?
- php - 表单没有发送任何值
- java - 从类的“数组版本”到Java中具有反射的类
- c# - AES 解密在 python 中有效,但在 .NET 中无效
- php - 我想通过单击超链接从 db 按名称而不是按 id 获取数据
- android - 如何设置TextInputLayout的轮廓框浮动提示背景颜色
- typescript - 使用“对象名称中的键”时设置键类型
- php - Laravel从帖子模型belongsTo关系中获取用户角色
- listview - 在 Nativescript-vue 中更改 ListView 中所选项目的背景颜色