MVC Dataannotation validation rule for a collection?

拈花ヽ惹草 提交于 2019-12-07 08:13:53

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4340205/mvc-dataannotation-validation-rule-for-a-collection

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