开发者

c# Validation approach

开发者 https://www.devze.com 2022-12-27 06:15 出处:网络
The scenario is like this: There are 4 controls, two drop downs, two date pickers and some validation rules. One is master drop down

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 dro开发者_高级运维pdown)
       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.


There is nothing wrong with your approach


Use a Validator factory.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号