Link to home
Start Free TrialLog in
Avatar of San24
San24

asked on

Control Validation Simple

Experts,

I`m using VS 2008 C# 3.5, Windows Forms    

I`m trying to validate some controls. For the sake of simlicity I`m using two text boxes as an example here. When the text boxes are validated either at the ValidateForm() method or the TextBox_leave event the values are assigned [HStart and HEnd]. Then I need to check some conditions based on the HStart and the HEnd values, the way I`m doing it right now is in ValidateForm() method. I would like to do this condition check in the HStartValidate() or HEndValidate() itself so that these are called when the focus leaves the Textboxes.
   
The way it is structured right now is a two tier validation. Validate and assign values, and then do another validation based on the assigned values. Can I make this into a single tier, a more concise and better way to do it. If you have a 20-30 text boxes, this just becomes too hard to manage.
   
    Here is the code.
     
       
       
        //Start
        private double hStart = Settings.Default.HFibStartSet;
        public double HStart
        {
            get
            {
                return hStart;
            }
            set
            {
                hStart = value;
            }
        }

        public String HStartTB
        {
            get
            {
                return HStartTBox.Text;
            }
            set
            {
                HStartTBox.Text = value;
            }
        }

        private bool HStartValidate(UnitsClass.UClass UnitObj)
        {
            if (HStartTB.Length <= 0)
            {
                ErrProXUserCntrl.SetError(HStartTBox, "Enter the  Start Position");
                return false;
            }
            else if (Convert.ToDouble(HStartTB) < (GlobalParam.LowLim * UnitObj.UnitConv) || Convert.ToDouble(HStartTB) > (GlobalParam.HighLim * UnitObj.UnitConv))
            {
                ErrProXUserCntrl.SetError(HStartTBox, "Out of Bounds!  start position should be between " + (GlobalParam.LowLim * UnitObj.UnitConv) + UnitObj.UnitStr + " and " + (GlobalParam.HighLim * UnitObj.UnitConv) + UnitObj.UnitStr);
                return false;
            }
            else
            {
                HStart = Convert.ToDouble(HStartTB);
                ErrProXUserCntrl.SetError(HStartTBox, String.Empty);
                return true;
            }
        }

        private void HStartTBox_Leave(object sender, EventArgs e)
        {
            HStartValidate(UnitsClass.GetUnits(XMetricUserCntrl.MetricFlag));
        }

        //End
        private double hEnd = Settings.Default.HFibEndSet;
        public double HEnd
        {
            get
            {
                return hEnd;
            }
            set
            {
                hEnd = value;
            }
        }

        public String HEndTB
        {
            get
            {
                return HEndTBox.Text;
            }
            set
            {
                HEndTBox.Text = value;
            }
        }

        private bool HEndValidate(UnitsClass.UClass UnitObj)
        {
            if (HEndTB.Length <= 0)
            {
                ErrProXUserCntrl.SetError(HEndTBox, "Enter the  End Position");
                return false;
            }
            else if (Convert.ToDouble(HEndTB) < (GlobalParam.DumVarOne * UnitObj.UnitConv) || Convert.ToDouble(HEndTB) > (GlobalParam.DumVarTwo * UnitObj.UnitConv))
            {
                ErrProXUserCntrl.SetError(HEndTBox, "Out of Bounds!  end position should be between " + (GlobalParam.DumVarOne * UnitObj.UnitConv) + UnitObj.UnitStr + " and " + (GlobalParam.DumVarTwo * UnitObj.UnitConv) + UnitObj.UnitStr);
                return false;
            }
            else
            {
                HEnd = Convert.ToDouble(HEndTB);
                ErrProXUserCntrl.SetError(HEndTBox, String.Empty);
                return true;
            }
        }

        private void HEndTBox_Leave(object sender, EventArgs e)
        {
            HEndValidate(UnitsClass.GetUnits(XMetricUserCntrl.MetricFlag));
        }
       
       
        //Validation Function
        public bool ValidateForm()
        {
            List<bool> XParamErrorBoolList = new List<bool>();
           
            XParamErrorBoolList.Add(HStartValidate(UCObj));
            XParamErrorBoolList.Add(HEndValidate(UCObj));

            if (XParamErrorBoolList.All(X => X))
            {
                bool VBool = false;

                if (HStart > HEnd)
                {
                    ErrProXUserCntrl.SetError(HStartTBox, "Start position cannot be greater than than the end position");
                }
                else
                {
                    VBool = true;
                }

                return VBool;
            }
            else
            {
                return false;
            }
        }

Ideas and suggestions are greatly appreciated.

Best,
San
       
Avatar of kris_per
kris_per


TextBox itself is having an 'Validating' event. If validation is ok, then you can allow the focus to leave the control. If not valid, then you can cancel the leaving and focus will remain in the textbox. See if using 'Validating' event will solve your issue...

=> http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(VS.71).aspx
Avatar of San24

ASKER

@Kris - I`ve used Validating events in the past, I don`t want to cancel the event. Leave event works better.
ASKER CERTIFIED SOLUTION
Avatar of kris_per
kris_per

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of San24

ASKER

@Kris - Trying your approach now.

I got some working code for simplified validation...Hope this helps...
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public partial class Form7 : Form
    {
        private Position _position = new Position();

        public Form7()
        {
            InitializeComponent();

            textBoxStartPos.Tag = "StartPos";
            textBoxEndPos.Tag = "EndPos";

            this.textBoxStartPos.Leave += new System.EventHandler(this.textBox_Leave);
            this.textBoxEndPos.Leave += new System.EventHandler(this.textBox_Leave);

            this.textBoxStartPos.TextChanged += new System.EventHandler(this.textBoxStartPos_TextChanged);
            this.textBoxEndPos.TextChanged += new System.EventHandler(this.textBoxEndPos_TextChanged);
        }

        private void textBoxStartPos_TextChanged(object sender, EventArgs e)
        {
            double start = 0;

            double.TryParse(textBoxStartPos.Text, out start);

            _position.Start = start;
        }

        private void textBoxEndPos_TextChanged(object sender, EventArgs e)
        {
            double end = 0;

            double.TryParse(textBoxEndPos.Text, out end);

            _position.End = end;
        }

        private void textBox_Leave(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)sender;

            List<string> errors = ValidationProvider.Validate(_position, textBox.Tag as string);

            HandleErrors(errors);
        }

        private void buttonValidateForm_Click(object sender, EventArgs e)
        {
            ValidateForm();
        }

        public void ValidateForm()
        {   
            List<string> allErrors = ValidationProvider.Validate(_position, ""); // pass empty string for fieldtag to validate all fields

            HandleErrors(allErrors);
        }

        private void HandleErrors(List<string> errors)
        {
            if (errors.Count > 0)
            {
                // process errors as required 
                // for example show them in another control
                // OR .net has ErrorProvider control which can be used
                // to show a red warning circle near the control having the error.

                textBoxErrors.Lines = errors.ToArray(); // textBoxErrors.Multiline is set to true
            }
            else
            {
                textBoxErrors.Text = "";
            }
        }
    }
}

///////////////////////////////////////////////////
ValidationProvider.cs

using System.Collections.Generic;

namespace WindowsFormsApplication4
{
    public class Position
    {
        public double Start;
        public double End;
    }

    public class ValidationProvider
    {
        public static List<string> Validate(Position position, string fieldTag)
        {
            // if fieldTag is empty or null, then it means validate whole form;
            // otherwise validate only the field specified by the fieldTag

            bool validateAll = string.IsNullOrEmpty(fieldTag);

            List<string> errors = new List<string>();

            if (fieldTag == "StartPos" || validateAll)
            {
                ValidateStartPos(position, errors);
            }

            if (fieldTag == "EndPos" || validateAll)
            {
                ValidateEndPos(position, errors);
            }

            if (validateAll)
            {
                // any common validation here
            }

            return errors;
        }

        public static void ValidateStartPos(Position position, List<string> errorList)
        {
            if (position.Start == 0)
            {
                errorList.Add("Start Position must have value");
            }
            else if (position.Start < 50 || position.Start > 100)
            {
                errorList.Add("Start Position must be between 50 and 100");
            }
            else if (position.Start > position.End)
            {
                errorList.Add("Start position cannot be greater than End position");
            }
        }

        public static void ValidateEndPos(Position position, List<string> errorList)
        {
            if (position.End == 0)
            {
                errors.Add("End Position must have value");
            }
            else if (position.End < 50 || position.End > 100)
            {
                errors.Add("End Position must be between 50 and 100");
            }
            else if (position.End < position.Start)
            {
                errors.Add("End position cannot be lesser than Start position");
            }
        }
    }
}

Open in new window

Avatar of San24

ASKER

@ Kris .. Thanks for the code. I tried your code. First thing I notices was, if the StartPos text box has a value and the EndPos doesn`t have a value, the condition (position.Start > position.End) is passing, eventhough Position.End doesn`t have a value. But it doesn`t happen the other way i.e, when EndPos has a value and StartPos doesn`t. Doesn`t make sense.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

If 0 is a valid value, then you need to do something more like:

Use the value of -1 for 'user has not entered value' condition. Initialize Start and End values to -1 in Position class and in TextChanged events, if the entered value is not a valid number, then reset values to -1. Use this -1 value in Validate methods to identify, user hasn't entered any valid value.

Another option is to use nullable double types (like public double? Start;), where double can be set to null and use null value 'user has not entered value' condition.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of San24

ASKER

@Kris - Thats what I was thinking too, use a double? cause 0 is valid and you cannot use other values cause the boundary conditions will be checked. I`m trying to customize the approach to my needs, I`ll keep you updated.
Avatar of San24

ASKER

Solution reached.