I have a model like that:
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Public Class Product
Private _id As Integer
Private _name As String
Private _description As String
Private _unitPrice As Decimal
<Required(AllowEmptyStrings:=False)>
Public Property Title() As String
<Required(AllowEmptyStrings:=False)>
Public Property Id() As Integer
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Description() As String
Get
Return _description
End Get
Set(ByVal value As String)
_description = value
End Set
End Property
Public Property UnitPrice() As Decimal
Get
Return _unitPrice
End Get
Set(ByVal value As Decimal)
_unitPrice = value
End Set
End Property
End Class
And my code to validate:
Dim results As List(Of ValidationResult) = Nothing
Dim product As New Product
If Validator.TryValidateObject(product, New ValidationContext(product), results, True) Then
MessageBox.Show(123)
Else
MessageBox.Show(results.ToString())
End If
My questions are:
Why is the
results
variable alwaysNothing
and how can I get the error message fromresult
and know which property has an error?Why can
Title()
be validated butId()
cannot? And how can I makeId()
validated?