views:

59

answers:

2

The scenario is like this:

There are 4 controls, two drop downs, two date pickers and some validation rules. One is master drop down
Depending upon the value in master drop down, some validation rule will be applied on the two date pickers and the other drop down control.
This validation rules will trigger if user changes value in any of the four controls.

Error provider needs to be set on the last control edited.

I am thinking of creating one method for every validation rule. A master method with syntax:

Private void ValidateData(Control ctrl)
    {
       ClearAllErrors();
       switch(value value in master dropdown)
       case 'Value 1' : Rule1(ctrl)
       case 'Value 2' : Rule2(ctrl)
       ....
    }

And rule methods like this:

Private void Rule1(Control ctrl)
{
     //Rule Logic
     //Eg. Date in dropdown should between 5 days after the date in dropdown1 
     //and 3 days before the date in dropdown2. 
     //Set error provider on the control if rule breaks.
}

Now on validated events of any of the four control I will pass that control and call the ValidateData() method.

Idea is to keep the code maintainable. Can this approach be optimized in any manner or there is some better way to handle these sort of validations.

+1  A: 

Use a Validator factory.

thelost
Can you elaborate a little bit on how to implement the factory pattern in case of validations? Maybe some pseudo code?
Aseem Gautam
See the C# example in the link I provided. You could either return a boolean meaning the configuration is valid or invalid, or use an Exception-based approach.
thelost
Decent alternative but: We would need to create a new class for each rule which will implement some base class say ValidationBase. With number of rules increasing over time, seems the number of classes required will go over the roof.
Aseem Gautam
+1  A: 

There is nothing wrong with your approach

Daniel Dolz