繁体   English   中英

使用FluentValidation根据值验证对象

[英]Validate an object based on a value using FluentValidation

我的数据库中有一个具有特定规则设置的通用对象。 我想根据对象中的值在数据库中执行特定的规则设置。

例如,假设我有一个这样的对象

public class MyObject {
    public int Type { get; set; }
    public string Name { get; set; }
    public decimal? Value { get; set; }
}

现在,如果Type的值为0,那么我需要确保然后填充Name。 如果Type为1,那么我需要确保Name被填充并且超过50个字符,并且还需要Value进行填充。

这是一个基本示例,并且还有更多规则。 到目前为止,我有

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM