Validation Block - Validating in Base Object

Topics: Validation Application Block
Jun 15, 2007 at 9:07 PM
I'm having a problem figuring this one out.
I have a BaseBusinessObject. It defines a property named IsValid().
I have an object that inherits from BaseBusinessObject named Car. Car has a property named Price with a validator attribute.

If I call ..
Dim car As Car = New Car
Dim results As ValidationResults
results = Validation.Validate(car)
Then results.IsValid is False (as it should be)

If, in the base object's IsValid property, I call...
Dim results As ValidationResults
results = Validation.Validate(Me)
Return results.IsValid
Then results.IsValid is True (which it should not be)

Obviously the call to Validate(Me) is trying to validate based on the BaseBusinessObject type, not the Car type.

Any suggestions from anyone?
Jun 17, 2007 at 3:07 AM
This behavior is by design, but not necessarily obvious. By default the block uses the type the reference to determine which validators to load, not the actual type of the object. You can use different overloads to be more explicit about what validators to load by calling the ValidationFactory.CreateValidator(Type t, ...) overloads. When you validate directly from Validation.Validate you do not get this control.

Jun 18, 2007 at 4:37 PM
Thanks Tom.

For anyone else looking to do this, this is what I did...

In my BaseBusinessObject (which the other objects inherit from), I added this code

Public ReadOnly Property IsValid() As Boolean
Dim typeName As String
Dim validator As Validator

typeName = Me.GetType().AssemblyQualifiedName
validator = ValidationFactory.CreateValidator(Type.GetType(typeName))

Return validator.Validate(Me).IsValid
End Get
End Property