[英]Validate an object based on a value using FluentValidation
I have a generic object with particular rules setup in my database. 我的数据库中有一个具有特定规则设置的通用对象。 I would like to execute particular rules setup in the database, depending on a value within the object.
我想根据对象中的值在数据库中执行特定的规则设置。
For example, lets say i have an object like this 例如,假设我有一个这样的对象
public class MyObject {
public int Type { get; set; }
public string Name { get; set; }
public decimal? Value { get; set; }
}
Now if the value of Type is 0, then i need to make sure then Name is populated. 现在,如果Type的值为0,那么我需要确保然后填充Name。 If Type is 1, then i need to make sure Name is populated and over 50 chars, and also need Value to be populated.
如果Type为1,那么我需要确保Name被填充并且超过50个字符,并且还需要Value进行填充。
This is a basic example, and there are more rules as well. 这是一个基本示例,并且还有更多规则。 So far i have
到目前为止,我有
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(....);
}
}
}
But i do not know how to get the instance that is being validated. 但是我不知道如何获取正在验证的实例。
I really thing it does the job your looking for. 我的确很适合您的工作。
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");;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.