Generic Validation Rules

Generic Validation Rules

Old forum URL: forums.lhotka.net/forums/t/307.aspx


xal posted on Wednesday, June 07, 2006

Following with the changes to validation rules I mentioned here, here's an implementation of generic rules:

In order to do this I created:
  Public Interface IRuleMethod
    ReadOnly Property RuleName() As String
    ReadOnly Property RuleArgs() As RuleArgs
    Function Invoke(ByVal target As Object) As Boolean
  End Interface

The rule handler was changed to this:

 Public Delegate Function RuleHandler(Of T, C As RuleArgs)( _
    ByVal target As T, ByVal e As C) As Boolean

There are many overloads of the AddRule() method with generic parameters besides the standard ones that we all use.

The benefits:

1) No code breaks. (This is because of the overloads in ValidationRules, ValidationRulesManager and SharedValidationRules.
2) You can write rules like:

  Public Class SomeClass(Of T As SomeClass(Of T))
    Inherits ActiveObjects.ActiveBusinessBase(Of T)

  Private mSomeNumber as Integer = 0
  Private Shared Function MyRule(ByVal target As SomeClass(Of T), _
            ByVal e As Csla.Validation.RuleArgs) As Boolean
    e.Description = "The number cannot be zero"
    Return target.mSomeNumber <> 0
  End Function
 
  Public Property SomeNumber as Integer
   ...
  End Property

  Shared Sub New
    Csla.Validation.SharedValidationRules.AddRule(Of SomeClass(Of T))( _
          AddressOf MyRule, GetType(DateRangeChild(Of T)), "SomeNumber")
  End Sub

  End Class

Note that the target of the rule has the same definition as the class (this can be done with generic and non generic classes, of course) and the overloading also applies to instance or type rules.

I'm attaching the whole Validation Namespace classes so that it you can check it out. This includes the fix mentioned in the other thread.

Andrés



xal replied on Thursday, June 08, 2006

Hey Rocky,
Here's Version 2 based on the latest csla. I cleaned it up a little bit and ported the comments to the new methods. Note that there's a IRuleMethod.vb file that needs to be added to the project.


Andrés

xal replied on Wednesday, June 14, 2006

Fixed a ValidationRules.vb because the overloads where not being called correctly.

Copyright (c) Marimer LLC