Existuje pravidlo na overenie pravosti údajov pre vlastnosť založenú na zbere?
Mám nasledujúce
<DisplayName("Category")>
<Range(1, Integer.MaxValue, ErrorMessage:="Please select a category")>
Property CategoryId As Integer
<DisplayName("Technical Services")>
Property TechnicalServices As List(Of Integer)
Hľadám validátor, ktorý môžem pridať do vlastníctva TechnicalServices a nastaviť minimálnu veľkosť kolekcie.
odpovede:
6 pre odpoveď č. 1Myslím, že niečo také môže pomôcť:
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;
}
}
Tam je priestor na zlepšenie, ale to je pracovný štart.
0 pre odpoveď č. 2
Ďalšou možnosťou .NET 4 by bolo vytvoriť vlastnú triedu (ktorá obsahuje príslušnú zbierku nehnuteľností) IValidatableObject, ako napríklad:
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
Na Validator v DataAnnotations bude automaticky volať tejto metódy overiť pre všetky IValidatableObjects.