Question

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?

Était-ce utile?

La solution

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
       }
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top