2011-01-11 60 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); 
    } 
}