【问题标题】:FluentValidation: Validating list of objects inheriting the same base classFluentValidation:验证继承相同基类的对象列表
【发布时间】:2023-02-21 18:08:28
【问题描述】:

我有一组继承相同基类的类。每个具体类都有自己的验证类。另一个类有一个基类的集合,我想用具体的验证器验证每个元素。

爬网时,我在 FluentValidation GitHub 问题跟踪器上找到了 question。解决方案是使用子验证器适配器.不幸的是,他们 changed 类,因此它使用通用方法。也有了这个改变适当的价值在 IValidationContext 上不再可用,这将允许检索每个条目的当前类型。

考虑用 *.SetValidator(new ...).When(...) 或 ChildRules 来解决它。但是根据我的理解,这两种方式在这种情况下都无济于事。

任何提示需要什么才能使用版本 11 实现这种验证行为?

public abstract class Base { ... }

public class A : Base {}
public class AValidator : AbstractValidator<a> { ... }

public class B : Base {}
public class BValidator : AbstractValidator<a> { ... }

public class SomeOther
{
   List<Base> Elements { get; set; } = new List<Base>();
}
public class SomeOtherValidator : AbstractValidator<SomeOther>
{
   public SomeOtherValidator()
   {
      // use AValidator or BValidator dependend on the concrete type of each element
      RuleForEach(x => x.Elements).SetValidator(??);
   }
}

【问题讨论】:

    标签: c# fluentvalidation


    【解决方案1】:

    Inheritance Validation 上的 FluentValidation 文档有这个例子:

    public class ContactRequestValidator : AbstractValidator<ContactRequest>
    {
      public ContactRequestValidator()
      {
    
        RuleForEach(x => x.Contacts).SetInheritanceValidator(v => 
        {
          v.Add<Organisation>(new OrganisationValidator());
          v.Add<Person>(new PersonValidator());
        });
      }
    }
    

    对于类 PersonOrganisation 实现一个通用的 IContact 接口。

    根据文档,这也应该适用于抽象基类:

    从 FluentValidation 9.2 开始,如果您的对象包含一个属性这是一个基类或接口,您可以为各个子类/实现器设置特定的子验证器。

    适合您的情况的是

    public class SomeOtherValidator : AbstractValidator<SomeOther>
    {
       public SomeOtherValidator()
       {
          // use AValidator or BValidator dependend on the concrete type of each element
          RuleForEach(x => x.Elements).SetInheritanceValidator(v =>
          {
               v.Add<A>(new AValidator());
               v.Add<B>(new BValidator());    
          });
       }
    }
    

    至少那是我阅读该文档的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多