2017-09-18 34 views
0

我一直在試圖找到一種方法來驗證列表中的項目,每個項目都有不同的驗證規則。我遇到了流暢的驗證,這是一個很棒的庫,但我似乎找不到單獨驗證每個項目的方法。我從這個類似的線程(Validate 2 list using fluent validation)中得到了一個微弱的想法,但我不確定如何將其集中在我想要的方式。流利的驗證,Asp.NET核心中的列表中的每個項目的不同驗證

所以我有這樣的視圖模型:

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

它包含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; } 
} 

的一點是,每個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

您正在從錯誤的角度接近驗證。而不是你的收集容器類中創建一個驗證條件,只是創建特定另一個驗證您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()); 
    } 
} 
+0

啊!我在另一篇文章中看到類似的東西,但認爲這不會起作用。無論如何,這完美的作品!謝謝! – Enixf