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?