How to avoid duplication of validation events Winforms

309 Views Asked by At

I am creating a project which will consist of three forms, one parent form which will be a decider on which form to load. Due to the two child forms being slightly similar, a lot of validation is the same. I have my methods for validation which are then called in the Validating event how can I minimise the amount of duplication in the Validating events and just have the one method with one validating event which has contol over all of my controls that share the method.

this is one example of my methods thats used extensively throughout:

public bool numValidation(string strNum)       
{
    if (!string.IsNullOrWhiteSpace(strNum))
    {
        int temp;
        if (int.TryParse(strNum, out temp))
        {
            MessageBox.Show("Phone Number is a valid input: " + temp);
            return true;
        }
        else
        {
            MessageBox.Show(temp + "Is not Valid input!!");                            
        }        
    }

    return false;
}

And this is just one of many of my Validating events :

private void txt_LndLine_Validating(object sender, CancelEventArgs e)
{
    numValidation(txt_LndLine.Text);
    txt_LndLine.Clear();
}

Just really wondering thoughts on how I could clean up the code and minimise duplication. Thanks in advance :)

2

There are 2 best solutions below

0
Marco Guignard On

If you have a lot of common stuff, Declarative Validation could help you to clean your code.

MSDN - Extending Windows Forms with a Custom Validation Component Library

You could also handle multiple control validating events with the same Sub, using an helper class to reuse a validation calculation function.

Last but not least, have a read about IDataErrorInfo. With this interface, you could put all validation algo in your business class.

It is working fine in Winforms with the ErrorProvider component and databinding

0
whatdoyouNeedFromMe On

Thanks to @Steve solved and better code. Was solved by creating a seperate static class and simply calling the method in all of my Validating Events in both pages that had the common functions.

  private void txt_Fax_Validating(object sender, CancelEventArgs e)
        {
            Utillity.numValidation(txt_Fax.Text);
            txt_Fax.Clear();

        }

And the Utillity Class was as follows:

public static bool numValidation(string strNum)
    {
        if (!string.IsNullOrWhiteSpace(strNum))
        {
            int temp;
            if (int.TryParse(strNum, out temp))
            {
                Console.WriteLine("Phone Number is a valid input: " + temp);
                return true;
            }
            else
            { Console.WriteLine(temp + "Is not Valid input!!"); }
        }
        return false;
    }