1

I am creating a C# Windows registration form, this means that a user have to enter his username, password and other particulars in order to sign up for an account.

So I used the "Validating" event with two "ErrorProviders" for each textbox to validate the textboxes (one for error, one for ok), to ensure that the username is at least 5 characters long, password at least consisting of 1 upper case, 1 lower case, etc, email format is correct... you get the idea.

The following is one of the validating code for my username textbox:

private void usrTxtBox_Validating(object sender, CancelEventArgs e)
{
    if (string.IsNullOrEmpty(usrTxtBox.Text))
    {
        usrOk.Clear();
        usrError.SetError(usrTxtBox, "field required!");
        count++;
    }
    else if (!Regex.IsMatch(usrTxtBox.Text, "</REGEX PATTERN/>"))
    {
        usrOk.Clear();
        usrError.SetError(usrTxtBox, "</ERROR MESSAGE/>");
        count++;
    }
    else
    {
        usrError.Clear();
        usrOk.SetError(usrTxtBox, "good to go");
        count = 0;
    }
}

That is repeated for every single textbox (i have username, password, name, email and contact number, each with a different regex pattern.

So as you all may know, the "Validating" event only validates when the textbox has been "Focused" and then "loses focus". Therefore, when i click "Register" by just correctly entering the required values for the first textbox, count would be equal to 0 and therefore, there would be no error. Code for register button click below:

private void rgstr_Click(object sender, EventArgs e)
{
    if (ValidateChildren())
    {
        if (count != 0)
        {
            MessageBox.Show("check again");
        }
        else if (count == 0)
        {
            MessageBox.Show("gd to go");
        }
    }
}

I tried using ValidateChildren to force validation but it doesn't work. Is there any solutions for this? Or is there an alternate solution for validating my textbox?

winston
  • 39
  • 1
  • 11
  • Welcome to Stack Overflow! I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles – Katie Kilian Jan 15 '14 at 15:54
  • Ah, I'm sorry, will take note for my future questions. Thanks – winston Jan 15 '14 at 15:56
  • http://stackoverflow.com/questions/8915151/c-sharp-validating-input-for-textbox-on-winforms ? Are you sure you cancel the event if it is not valid? e.Cancel() ? It might validate correctly but have no reaction to it. What is the problem? Does validate wrong input or marks everything incorrect? – wondra Jan 15 '14 at 16:01
  • I did not use e.Cancel(). Sorry i'm relatively new to C#, and i don't really know what e.Cancel() does. The problem is that when I submit the form only by entering stuff into the one textbox (which means the other textboxes are not validated as they have not been focused) by clicking on the "Register" button on my WinForm, the program assumes that all the textboxes have been validated as the count = 0. – winston Jan 15 '14 at 16:08
  • e.Cancel() cancels the action. Also I would re-validate every textbox on click exactly because of what you said. – wondra Jan 15 '14 at 16:16
  • won't that make the "Validating" event for every textbox unnecessary? – winston Jan 15 '14 at 16:21
  • Just out of curiosity, is the Button a ToolStripButton ? – Luc Morin Jan 15 '14 at 16:33
  • @mrlucmorin no it is just a normal button – winston Jan 15 '14 at 16:44

1 Answers1

1

Try this pattern for validation

private bool ValidateChildren()
 {
   bool IsValid = true;
   // Clear error provider only once.
   usrError.Clear(); 

   //use if condition for every condtion, dont use else-if
   if (string.IsNullOrEmpty(usrTxtBox.Text.Trim()))
      {
       usrError.SetError(usrTxtBox, "field required!"); 
       IsValid =false;              
      }

   if (!Regex.IsMatch(usrTxtBox.Text, "</REGEX PATTERN/>"))
      {            
       usrError.SetError(usrTxtBox, "</ERROR MESSAGE/>");
        IsValid =false; 
      }
    return IsValid ;
  }

and int the button Click:

   private void rgstr_Click(object sender, EventArgs e)
    {
      if (ValidateChildren())
        {
          // valid
        }
      else
       {
         //Error will shown respective control with error provider
       }
    }
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
  • hi i got the error from the "private bool ValidateChildren()" which says "not all code paths return a value". also, "bool IsValue" is assigned but its value is never used – winston Jan 15 '14 at 16:23
  • hey thanks, it worked, i have made some changes to the code myself though. I changed the name of ValidateChildren() as it is a WinForm method(?) which will clash. Thanks for the help! Much appreciated. – winston Jan 15 '14 at 16:58
  • sorry, but an additional question here. Why can't i use an if-else statement for the validation above? If i just used if statement for each condition, then won't the second if statement "overwite" the first if statement? Meaning if i left it blank, it fits the first condition (IsNullOrEmpty) and the second condition (Regex Pattern), hence, it would show the error from the second condition instead from the first. – winston Jan 15 '14 at 17:04
  • you can use, but if it is for multiple textbox then, you have to check each textbox with if condition. – Mohammad Arshad Alam Jan 15 '14 at 17:08