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?
CodePudding user response:
Why is the
results
variable alwaysNothing
and how can I get the error message fromresult
and know which property has an error?
When the validationResults
parameter is null, the validation stops at the first error and no errors are added to the collection. If you want it to hold a collection of failed validations, you must initialize the collection before passing its reference:
Dim results As New List(Of ValidationResult)
Why can
Title()
be validated butId()
cannot? And how can I makeId()
validated?
Title
is a String, which is a reference type whose default value is null (AKA, Nothing
), while Id
is an Integer, which is a value type whose default value is 0. So, the RequiredAttribute
makes no sense here since the property will always have a value. You may change its type to a Nullable(Of Integer)
if you want it to work with the RequiredAttribute
:
Public Property Id As Integer?