【问题标题】:Fluent Validations. Inherit validation classes流利的验证。继承验证类
【发布时间】:2016-06-23 04:07:22
【问题描述】:

我使用了 Fluent Validator。但有时我需要创建规则层次结构。例如:

[Validator(typeof(UserValidation))]
public class UserViewModel
{
    public string FirstName;
    public string LastName;
}

public class UserValidation : AbstractValidator<UserViewModel>
{
    public UserValidation()
    {
        this.RuleFor(x => x.FirstName).NotNull();
        this.RuleFor(x => x.FirstName).NotEmpty();

        this.RuleFor(x => x.LastName).NotNull();
        this.RuleFor(x => x.LastName).NotEmpty();
    }
}

public class RootViewModel : UserViewModel
{
    public string MiddleName;       
}

我想将验证规则从 UserValidation 继承到 RootValidation。但是这段代码不起作用:

public class RootViewModelValidation:UserValidation<RootViewModel>
{
    public RootViewModelValidation()
    {
        this.RuleFor(x => x.MiddleName).NotNull();
        this.RuleFor(x => x.MiddleName).NotEmpty();
    }
}

如何使用 FluentValidation 继承验证类?

【问题讨论】:

    标签: c#-4.0 fluentvalidation


    【解决方案1】:

    要解决此问题,您必须将 UserValidation 类更改为泛型。请参阅下面的代码。

    public class UserValidation<T> : AbstractValidator<T> where T : UserViewModel
    {
        public UserValidation()
        {
            this.RuleFor(x => x.FirstName).NotNull();
            this.RuleFor(x => x.FirstName).NotEmpty();
    
            this.RuleFor(x => x.LastName).NotNull();
            this.RuleFor(x => x.LastName).NotEmpty();
        }
    }
    
    [Validator(typeof(UserValidation<UserViewModel>))]
    public class UserViewModel
    {
        public string FirstName;
        public string LastName;
    }
    
    public class RootViewModelValidation : UserValidation<RootViewModel>
    {
        public RootViewModelValidation()
        {
            this.RuleFor(x => x.MiddleName).NotNull();
            this.RuleFor(x => x.MiddleName).NotEmpty();
        }
    }
    
    [Validator(typeof(RootViewModelValidation))]
    public class RootViewModel : UserViewModel
    {
        public string MiddleName;
    }
    

    【讨论】:

    • 我个人会尝试将 UserValidation 抽象化。但是这样就已经很棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 2013-01-21
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多