开发者

MVC Dataannotation validation rule for a collection?

开发者 https://www.devze.com 2023-01-29 02:33 出处:网络
Is there a dataannotation validate rule for a collection based property? I have the following <DisplayName(\"Category\")>

Is there a dataannotation validate rule for a collection based property?

I have the following

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

  <开发者_开发问答DisplayName("Technical Services")>
  Property TechnicalServices As List(Of Integer)

I'm looking for a validator that i can add to the TechnicalServices property to set a minimum for the collection size.


I think something like this might help:

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

There's room for improvement, but that's a working start.


Another option from .NET 4 onward would be to make the class itself (which contains the collection property in question) implement IValidatableObject, such as:

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

The Validator in DataAnnotations will automatically call this Validate method for any IValidatableObjects.

0

精彩评论

暂无评论...
验证码 换一张
取 消