2010-12-02 60 views
4

是否有基於集合的屬性的dataannotation驗證規則?MVC Dataannotation驗證規則的集合?

我有以下

<DisplayName("Category")> 
    <Range(1, Integer.MaxValue, ErrorMessage:="Please select a category")> 
    Property CategoryId As Integer 

    <DisplayName("Technical Services")> 
    Property TechnicalServices As List(Of Integer) 

我在尋找,我可以添加到TechnicalServices屬性設置爲集合尺寸最小的一個驗證。

回答

6

我覺得這樣的事情可能會有所幫助:

public class MinimumCollectionSizeAttribute : ValidationAttribute 
{ 
    private int _minSize; 
    public MinimumCollectionSizeAttribute(int minSize) 
    { 
     _minSize = minSize; 
    } 

    public override bool IsValid(object value) 
    { 
     if (value == null) return true; 
     var list = value as ICollection; 

     if (list == null) return true; 

     return list.Count >= _minSize; 
    }  
} 

有改進的餘地,但是這是一個工作的開始。

+0

好答案CGK! – Francisco 2011-04-11 21:13:03

0

從.NET 4的另一種選擇以後將是使類本身(其中包含在問題集合屬性)實現IValidatableObject,如:

Public Class SomeClass 
    Implements IValidatableObject 

    Public Property TechnicalServices() As List(Of Integer) 
     Get 
      Return m_TechnicalServices 
     End Get 
     Set 
      m_TechnicalServices = Value 
     End Set 
    End Property 
    Private m_TechnicalServices As List(Of Integer) 

    Public Function Validate(validationContext As ValidationContext) As IEnumerable(Of ValidationResult) 
     Dim results = New List(Of ValidationResult)() 

     If TechnicalServices.Count < 1 Then 
      results.Add(New ValidationResult("There must be at least one TechnicalService")) 
     End If 

     Return results 
    End Function 
End Class 

在DataAnnotations的Validator會自動調用這個方法驗證對於任何有價值的物品。