MVC Dataannotation validation rule for a collection?

和自甴很熟 提交于 2019-12-05 13:34:31

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!