代码之家  ›  专栏  ›  技术社区  ›  Enixf

流畅的验证,在Asp中对列表中的每个项目进行不同的验证。净核心

  •  4
  • Enixf  · 技术社区  · 7 年前

    Validate 2 list using fluent validation

     public class EditPersonalInfoViewModel
    {
        public IList<Property> UserPropertyList { get; set; }
    }
    

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

    重点是,每个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
                            }
                      }
              )
    
        }
    }
    

    1 回复  |  直到 7 年前
        1
  •  7
  •   Federico Dipuma    7 年前

    您从错误的角度进行验证。不要在集合容器类中创建验证条件,只需为您的 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());
        }
    }