Search code examples
c#.netvalidationdesign-patternsreusability

Minimize coding for validation in C#


I'm trying to validate a set of Textboxes in a winform application.

if(string.IsNullOrEmpty(txtCarbohydrate.Text){

            //todo
        }

but there are several Textboxes in my form to be validated for emptiness , not only in the current win form but other forms too. how can i create a method or a class that can validate several Textboxes and be reusable across application?

EDIT : i wrote somthing like this , any suggestion to make it better ?

  class ValidateEmpty
  {
    bool res = false;
    //List<object> txt = new List<object>();
    List<string> st = new List<string>();

    public List<string> St
    {
        get { return st; }
        set { st = value; }
    }

    public ValidateEmpty(List<string> _str)
    {
        this.st = _str;
    }      

    public bool checkEmpty()
    {
        bool res = false;
        for (int i = 0; i < St.Count(); i++ )
        {
            if(string.IsNullOrEmpty(St[i]))
            {
                res= true;                   
            }
        }
            return res;
    }
}

} `


Solution

  • You could put them in a list and then loop through the list.

    List<TextBox> TextBoxes=new List<TextBox>() {txtCarbohydrate, txtProtein, txtFat};
    
    foreach(TextBox tb in TextBoxes)
    {
        if(String.IsNullOrEmpty(tb.Text)
        {
            //do something
        }
    }
    

    Based on your edit, you want to return a Boolean (it's really hard to understand your code and what you're trying to accomplish, you need to be clear and concise!) to indicate if a TextBox was empty or not. Here's how you could create a method to do that...

    public static bool IsThereAnEmptyTextBox(List<TextBox> textBoxes)
    {
        bool emptyfound=false;
        foreach(TextBox tb in textboxes)
        {
            if(String.IsNullOrEmpty(tb.Text)
            {
                emptyfound=true;
            }   
        }
        return emptyfound;
    }
    

    You can call this function from any class, if you put this function in a Utility class or in a base class etc. If you want to combine it with paqogomez's answer you can call it from a form like this...

    bool emptyfound=MyUtilities.IsThereAnEmptyTextBox(myForm.Controls.OfType<TextBox>().ToList());
    

    I think this is a terrible way of going about it, but I'm trying to demonstrate how you could do what you've asked for.