Let's deal with
TxtEmail_Validating
first...
All those checks that could finally lead to the message "Email cannot be left blank" are a waste of time - if you choose an appropriate regex to test against.
But if you were going to leave them in, you need to exit appropriately once you have discovered that the validation has failed.
Also there is no need to set the focus to the control that you are validating because you have not yet left that control.
Finally, you went to all the trouble of trimming the text in the textbox, but didn't use it when matching to the regex.
Next - as per my comment, there is no need to turn autovalidation off while you are validating - it sort of defeats the purpose :-) The correct way to let the system know that the validation has failed is to use the
CancelEventArgs[
^] parameter provided - i.e. set
e.Cancel=true;
I found an appropriate regex
here[
^] and the following will validate your email text box for you (note I've set the email text to lower case to allow for a simpler regex - always a good idea in my opinion) ...
private void TxtEmail_Validating(object sender, CancelEventArgs e)
{
string StrEmail = TxtEmail.Text.Trim().ToLower();
Regex r = new Regex(@"\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\b");
if (!r.IsMatch(StrEmail))
{
MessageBox.Show("Invalid Email Format");
TxtEmail.Clear();
e.Cancel = true;
}
}
Now to your
TxtPassword
validation:
As per my comment - you have used the wrong event - you should be using
TxtPassword_Validating
not
Validated
All the comments regarding the TxtEmail validation also apply here, leaving us with code as follows
private void TxtPassword_Validating(object sender, CancelEventArgs e)
{
Regex r = new Regex(@"^[a-zA-Z]\w{3,14}$");
if (!r.IsMatch(TxtPassword.Text))
{
MessageBox.Show("Invalid Password");
TxtPassword.Clear();
e.Cancel = true;
}
}
You can still be left in a position where you haven't entered valid data, but you still want to close the form - see the solution from Sinisa Hajnal for a way around that, or my Tip
Allow Form to close when invalid data is present[
^]