Fluent Validation,对Asp.NET Core中列表中的每一项进行不同的验证

Eni*_*ixf 3 c# asp.net validation asp.net-mvc fluentvalidation

我一直试图找到一种方法来验证列表中的项目,每个项目都有不同的验证规则。我遇到了 Fluent 验证,这是一个很棒的库,但我似乎无法找到一种方法来单独对每个项目进行验证。我从这个类似的线程中得到了一个模糊的想法(使用 fluent 验证验证 2 列表),但我不确定如何按照我想要的方式关注它。

所以我有这个视图模型:

 public class EditPersonalInfoViewModel
{
    public IList<Property> UserPropertyList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这包含 Active Directory 属性的列表。每个由这个类表示:

   public class Property
{
    public string Name { get; set; }
    public UserProperties Value { get; set; }
    public string input { get; set; }
    public bool Unmodifiable  { get; set; }
    public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

关键是,每个 AD 属性都有不同的约束,所以我想以某种方式为列表中的每个属性指定不同的规则,如下所示:

   public class ADPropertiesValidator : AbstractValidator<EditPersonalInfoViewModel>
{
    public ADPropertiesValidator()
    {
        RuleFor(p => p.UserPropetyList).Must((p,n) =>
         {
              for (int i = 0; i < n.Count; i++)
                  {
                     if ((n[i].Name.Equals("sAMAccountName"))
                        {
                          RuleFor(n.input ).NotEmpty()....
                        }
                     else if(...)
                        {
                      //More Rules
                        }
                  }
          )

    }
}
Run Code Online (Sandbox Code Playgroud)

任何想法如何解决这个问题?提前致谢。

Fed*_*uma 5

您正在从错误的角度进行验证。不要在您的集合容器类中创建验证条件,只需为您的Property类创建另一个特定的验证器,然后在您的内部使用它ADPropertiesValidator

public class ADPropertyValidator : AbstractValidator<Property>
{
    public ADPropertyValidator()
    {
        When(p => p.Name.Equals("sAMAccountName"), () =>
        {
            RuleFor(p => p.input)
                .NotEmpty()
                .MyOtherValidationRule();
        });

        When(p => p.Name.Equals("anotherName"), () =>
        {
            RuleFor(p => p.input)
                .NotEmpty()
                .HereItIsAnotherValidationRule();
        });
    }
}

public class ADPropertiesValidator : AbstractValidator<EditPersonalInfoViewModel>
{
    public ADPropertiesValidator()
    {
        RuleForEach(vm => vm.UserPropertyList)
            .SetValidator(new ADPropertyValidator());
    }
}
Run Code Online (Sandbox Code Playgroud)