2011-01-11 48 views
0

我想了解如何驗證一組複選框。對複選框組的自定義驗證

我的模型:

[MinSelected(MinSelected = 1)] 
public IList<CheckList> MealsServed { get; set; } 

我希望能夠創建一個自定義的驗證,這將確保至少有1(或其他數字)複選框被選中。如果不是,則顯示ErrorMessage

#region Validators 

public class MinSelectedAttribute : ValidationAttribute 
{ 
    public int MinSelected { get; set; } 

    // what do I need to do here? 
} 

有人可以幫我解決這個問題嗎?

回答

1

您可以覆蓋IsValid方法,並確保該集合包含至少MinSelected項目進行IsChecked等於true(我想這CheckList類你有一個IsChecked屬性):

public class MinSelectedAttribute : ValidationAttribute 
{ 
    public int MinSelected { get; set; } 

    public override bool IsValid(object value) 
    { 
     var instance = value as IList<CheckList>; 
     if (instance != null) 
     { 
      // make sure that you have at least MinSelected 
      // IsChecked values equal to true inside the IList<CheckList> 
      // collection for the model to be valid 
      return instance.Where(x => x.IsChecked).Count() >= MinSelected; 
     } 
     return base.IsValid(value); 
    } 
}