Software solutions for a mobile world

Validating text box fields in any application has always been a pain, and I have always tried to use short-cuts to validate input. Windows Phone 7 is no exception, so hopefully this will help you ease through field validation.

My ideal method has always been to loop through the controls, and validate any text boxes I come across. To help me do this, I have always used the 'tag' property of the text box to determine what needs doing. I use a list of items in the tag, to determine what I need to validate. So, for a required numeric field for an 'order qty' for example, I would set the tag to "order qty,numeric". If I had a text box that must be entered, be numeric, and have a minimum value of 1 and a maximum value of 1000, then my tag would be "order qty,numeric,1,1000". This can be extended in any way you want, to check for numeric, alphabetic etc. etc. I have a routine called "valid_numeric_fields" which will test a passed string for numeric, min and max values and whether decimal places or negatives are acceptable.

The next step would be to loop through the controls in the form, or the panel or some container control. Prior to Windows Phone 7, I would just iterate through the controls collection, but as I soon found out, the rules changed in  Windows Phone 7. Not to panic though, it is still possible. In this sample, my text boxes are all contained in a "stackpanel", and all have textblocks for labels. The sample can be extended to use other controls, but here we will concentrate on text boxes. When the user clicks on the control to say the have filled in the form, we call a routine called "validatesok" which returns a Boolean.

We start by getting a count of the number of controls in our container control, in this case a stack panel, and declaring a text box to work with.

 int numChildren = VisualTreeHelper.GetChildrenCount(stackPanel1);
 TextBox txtControl = default(TextBox);

 Next we loop through the child controls in the stack panel

for (int childIndex = 0; childIndex < numChildren; childIndex++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(stackPanel1, childIndex);
                if (child.ToString() == "System.Windows.Controls.TextBox")
                {
                    txtControl = (TextBox)child;
                    try
                    {...

The above code loops through the controls in the stack panel and isolates any text box. Now that we know we are on a text box, we look at the tag property. We split the tag into individual elements, using the "," as the split character.

 if (txtControl.Tag.ToString().Length != 0)
      {
           string[] elements = txtControl.Tag.ToString().Split((new char[] { ',' }));

We set the tag to "order qty,numeric", so we know if the length of the text field is 0, nothing has been entered. We can display an error message, set the focus on the field in error, and exit the routine. 

if (txtControl.Text.Length == 0)
   {
       MessageBox.Show("Please enter a " + elements[0], "Required Field", MessageBoxButton.OK);
       txtControl.Focus();
       return false;
   }

Next, we can check if we need a numeric field. The routine 'Valid_Numeric_Field' takes several parameters, the value to check, accept decimals, accept negatives, max length, field name, min value and max value.

if (txtControl.Tag.ToString().ToUpper().Contains("NUMERIC"))
   {
      if (!utilities.Valid_Numeric_Field(txtControl.Text, false, false, 4, elements[0], 0, 1000))
         {
            MessageBox.Show("Please enter a valid numeric for " + elements[0], "Required numeric Field", MessageBoxButton.OK);
            txtControl.Focus();
            return false;
         }
   }

So taking the whole routine we have:-

private Boolean validatesOK()
        {

            int numChildren = VisualTreeHelper.GetChildrenCount(ContentPanel);
            TextBox txtControl = default(TextBox);
            for (int childIndex = 0; childIndex < numChildren; childIndex++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(ContentPanel, childIndex);
                if (child.ToString() == "System.Windows.Controls.TextBox")
                {
                    txtControl = (TextBox)child;
                    try
                    {
                        if (txtControl.Tag.ToString().Length != 0)
                        {
                            string[] elements = txtControl.Tag.ToString().Split((new char[] { ',' }));
                            if (txtControl.Text.Length == 0)
                            {
                                MessageBox.Show("Please enter a " + elements[0], "Required Field", MessageBoxButton.OK);
                                txtControl.Focus();
                                return false;
                            }
                            if (txtControl.Tag.ToString().ToUpper().Contains("NUMERIC"))
                            {
                                if (!utilities.Valid_Numeric_Field(txtControl.Text, false, false, 4, elements[0], 0, 1000))
                                {
                                    MessageBox.Show("Please enter a valid numeric for " + elements[0], "Required numeric Field", MessageBoxButton.OK);
                                    txtControl.Focus();
                                    return false;
                                }
                            }
                        }
                    }
                    catch
                    {

                    }
                }

            }

            return true;
        }

This may appear to be overkill for a couple of fields, but imagine if you are capturing bank details, names and addresses etc. By putting more into the tag of each textbox, and extending the 'validatesok' routine, you can do all your validation in one call. By using regular expressions, and the tag property, you can easily extend your validation

Even better, you could encapsulate the code into a library, and just call it when you are validating fields.

The above is just a starter, but should make validating your input forms on Windows Phone 7 slightly easier.

Originally posted 20/Feb/2011

Contact

M: +44 (0)7860 907493
B:  +44 (0)1204 657497

pete@gui-innovations.com

More

Connections

   

Twitter Feed