验证孙子对象的替代方法



我的对象图的图超过两个级别。它代表了一个有孩子和孙子的实体(总计):

A → B → C

我想在图表的所有级别上验证。我知道我可以使用Must()的过载或使用Custom()规则验证 b 时访问 a 。我还没有想出如何使用这两种技术来访问 a c 的验证器访问,因为似乎没有上下文。

我想做的唯一途径是创建一个新的对象,该对象是一种扁平的表示。换句话说,创建一个包装器,将 a c 放置在同一级别上,这使我可以在 c 上使用Must()过载来到达 a 在伪 - 父母包装器

Wrapper → A → B → C
        → C

问题是我必须创建另一个验证器(在这种情况下为包装器)。我宁愿将我的所有验证逻辑保存在一起。

有其他方法吗?

我试图将您的案例放在代码中,以便我们可以努力并找到解决方案。

using FluentValidation;
namespace FluentDemo
{
    class Program
    {
        static void Main(string[] args) 
        {
            // TODO
        }
    }
    class A
    {
        public string MyProperty { get; set; }
    }
    class B
    {
        public string OtherProperty { get; set; }
        public A A { get; set; }
    }
    class C
    {
        public string DifferentProperty { get; set; }
        public B B { get; set; }
    }
    class AValidator : AbstractValidator<A>
    {
        public AValidator()
        {
            RuleFor(a => a.MyProperty)
                .NotNull(); 
        }
    }
    class BValidator : AbstractValidator<B>
    {
        public BValidator(IValidator<A> aValidator)
        {
            RuleFor(b => b.OtherProperty)
                .NotNull();
            RuleFor(b => b.A)
                .SetValidator(aValidator);
        }
    }
    class CValidator : AbstractValidator<C>
    {
        public CValidator(IValidator<B> bValidator)
        {
            RuleFor(c => c.DifferentProperty)
                .NotNull();
            RuleFor(c => c.B)
                .SetValidator(bValidator);
        }
    }
}

最新更新