Dynamic Validation Rules

Dynamic Validation Rules

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

RogerWillCode posted on Thursday, May 27, 2010

Here's the situation, I have a few CommonRules.StringRequired Validation rules that are common for certain properties of my object regardless.  At times though I have some properties that are required based on one particular property.  I am trying to decide if I can easily add some Validation Rules for the properties in question dynamically based on the driver value or if I need to create some inheritance objects (which I don't really want to do).

Overly simplistic example:

WidgetTypeDescription Property (driver property) - values: Widget 1, Widget 2, Widget 3

OwnerProperty (Required for all) - values: Bob, Will, Joe, Jane

PrimaryMaterialProperty (Required for all) - values: wood, plastic, steel

SecondaryMaterialProperty (Only required if we are dealing with Widget 3)


RockfordLhotka replied on Thursday, May 27, 2010

The philosophy behind the CSLA rules system is to make the rules smart, not to make the adding of the rules smart.

In other words, if you have a rule that should behave differently (such as running or not running) based on various object state information, then you should write your rule to be smart enough to do the right thing based on the state of the object.

The rules in CommonRules are for the trivial case. As soon as you move behind the trivial case, you should write your own rules that handle your specific situation.

RogerWillCode replied on Friday, May 28, 2010

Can't ask for more than an answer from the source.  Thanks for taking the time to answer Rocky.  I think I got the custom rule working just fine.  I always look for the best/easiest (not always the same) way to do things.

 Basically what I did (in case someone else is looking to do something similar) is this:

Added one line for each of the properties that may or may not be required in the AddBusinessRules() method


>(Required<BusinessObject>, new Csla.Validation.RuleArgs (PropertyNameProperty));

Then I defined the custom rule:


private static bool Required<T>(T target, Csla.Validation.RuleArgs e) where T : BusinessObject



switch (target.ReadProperty(BusinessObjectTypeIDProperty))



     case 1:


     switch (e.PropertyName)



           case "AdditionalMaterialID":


           case "SomeOtherRequiredProperty":

                 e.Description =

string.Format(Csla.Properties.Resources.StringRequiredRule, "Value");


                 return false;




                 return true;


     case 2:

     //similar code


          return true;


}// end of custom rule Required


Copyright (c) Marimer LLC