使用FluentValidation根据值验证对象
本文关键字:验证 对象 FluentValidation 使用 | 更新日期: 2023-09-27 18:32:33
我的数据库中有一个具有特定规则设置的通用对象。 我想在数据库中执行特定的规则设置,具体取决于对象中的值。
例如,假设我有一个这样的对象
public class MyObject {
public int Type { get; set; }
public string Name { get; set; }
public decimal? Value { get; set; }
}
现在,如果 Type 的值为 0,那么我需要确保填充 Name。 如果类型为 1,那么我需要确保填充 Name 并且超过 50 个字符,并且还需要填充值。
这是一个基本示例,并且还有更多规则。 到目前为止,我有
public class MyObjectValidator : AbstractValidator<MyObject>
{
public MyObjectValidator()
{
// here i would like to check what the value of type is, something like
if (Type == 1) {
RuleFor(e => e.Name).NotEmpty().WithMessage("Please enter a name");
}
if (Type == 2) {
RuleFor(....);
}
}
}
但是我不知道如何获取正在验证的实例。
我真的认为它可以完成您想要的工作。
public class MyObjectValidator : AbstractValidator<MyObject>
{
public MyObjectValidator()
{
RuleFor(x => x.Name).NotEmpty().When(m => m.Type == 1).WithMessage("your msg");
RuleFor(x => x.Name).Must(s => s.Length > 50).When(m => m.Type == 2).WithMessage("your msg");;
}
}