是否有基于集合的属性的数据注释验证规则?
我有以下
<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属性的验证器来设置集合大小的最小值。
答案 0 :(得分: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;
}
}
还有改进的余地,但这是一个有效的开始。
答案 1 :(得分: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将自动为任何IValidatableObjects调用此Validate方法。