【问题标题】:MVC Dataannotation validation rule for a collection?集合的MVC Dataannotation验证规则?
【发布时间】:2010-12-02 21:35:39
【问题描述】:
对于基于集合的属性是否有数据注释验证规则?
我有以下
<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 属性以设置集合大小的最小值的验证器。
【问题讨论】:
标签:
vb.net
validation
asp.net-mvc-2
data-annotations
【解决方案1】:
我认为这样的事情可能会有所帮助:
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;
}
}
还有改进的余地,但这是一个工作的开始。
【解决方案2】:
从 .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 会自动为任何 IValidatableObjects 调用此 Validate 方法。