Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Following is the code snippet that I am using to validate my textboxes.

C# Code

C#
private void TxtEmail_Validating(object sender, CancelEventArgs e)
{

    string StrEmail = TxtEmail.Text.Trim();
    if (StrEmail == "" || StrEmail.IndexOf("") > 0 || StrEmail.IndexOf('"') > 0 || StrEmail == " " || StrEmail.IndexOf(" ") > 0)
    {
        MessageBox.Show("Email Cannot be Left Blank");
        TxtEmail.Select();

    }

    Regex r = new Regex(@"@.");

    if (r.IsMatch(TxtEmail.Text))
    {
        AutoValidate = AutoValidate.Disable;

    }
    else
    {
        MessageBox.Show("Invalid Email Format");
        TxtEmail.Clear();
        TxtEmail.Focus();
    }

 }

private void TxtPassword_Validated(object sender, EventArgs e)
{

    string StrPass=TxtPassword.Text;
    if (StrPass == "" || StrPass.IndexOf("") > 0 || StrPass.IndexOf('"') > 0 || StrPass == " " || StrPass.IndexOf(" ") > 0)
    {
        MessageBox.Show("Invalid Password");
        TxtPassword.Focus();
    }

    Regex r = new Regex(@"@#");
    if (r.IsMatch(TxtPassword.Text))
    {

        AutoValidate = AutoValidate.Disable;

    }
    else
    {
        MessageBox.Show("Invalid Password");
        TxtPassword.Clear();
        TxtPassword.Focus();

    }


}



I am using AutoValidate feature to cancel validation if the parameters within the Regex match.But the problem is when I use AutoValidate or Set CauseValidation to false,the validation of TextBox is done the first time the form is loaded. But when I remove the text within the texbox and re-enter it, validation doesn't work the 2nd time and does not throw the message "Invalid Email"

In the case of Password Validation.Even after entering password as per the parameters within the Regex,it throws "Invalid Password" message.I saw questions here based on validation but none of them have satisfactory solution to my question.

Can anyone help me to rectify this error? I want to achieve Validation without ErrorProvider which is another option.
Posted
Comments
CHill60 22-Oct-14 7:44am    
Why are you validating the password in the Validated event, it should be in Validating event instead - might help.
Also why are you turning AutoValidate off? use e.Cancel=True if the textbox fails validation
Sinisa Hajnal 22-Oct-14 7:55am    
You can replace testing for empty string with IsNullOrEmpty function of string class.

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) ...
C#
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
C#
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[^]
 
Share this answer
 
Comments
BillWoodruff 22-Oct-14 12:04pm    
+5
vivek murli 23-Oct-14 3:33am    
Thanks CHILL60 :)
vivek murli 23-Oct-14 10:33am    
@CHILLI 60. I have an issue with closing the form on Click of Cancel Button.I referred your link regarding that.

I entered the following code inside Cancel button

private void btnCancel_click(object sender,EventArgs e)
{
form1 f1=new form1();
btnCancel.CausesValidation=true;
f1.close()
}


private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = false;
}

Please suggest

Thanks
CHill60 23-Oct-14 10:35am    
What is the issue?
vivek murli 23-Oct-14 10:38am    
On click of cancel button ,Validation takes place.The main form is supposed to close after clicking cancel.But validation event is triggered even after entering CausesValidation inside the button
Here is resolved problem[^]

If this helps, please take time to accept the solution. Thank you.
 
Share this answer
 
Comments
CHill60 22-Oct-14 8:24am    
vivek murli 23-Oct-14 3:34am    
Thank u :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900