Thursday, November 29, 2012

Email validation using ErrorProvider in C# Windows Application

C# Windows Application provides an ErrorProvider control, which is similar to the ValidationSummary control in Asp.Net, this control consolidates all the error messages in the form and alerts the user on the Form errors.

In this post we shall see on how to use the ErrorProvider control to validate Email in a C# Windows Form.

1. Create a new / open an existing C# Windows application
2. Open and existing / Add a new Windows Form to the Project
3. Add the required controls to the Form, let us add a Textbox for Email.
4. Open the ToolBar, Drag an ErrorProvider control into the form.
5. The ErrorProvider control can be found in the Components section.
5. The control gets added to the control tray at the bottom of the Form in the Design View.
6. Provide a name to the ErrorProvider, let us give is as errSummary
7. Now write a method which will perform the validation using RegularExpression

private void ValidateEmail()

{
    Regex regEmail = new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+"
                            + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                            + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                            + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                            + @"[a-zA-Z]{2,}))$",
                            RegexOptions.Compiled);

    if (!regEmail.IsMatch(txtEmail.Text))
    {
        errSummary.SetError(txtEmail, "Please enter a Valid Email Address.");
        boolFormValid = false;
        return;
    }
    else
    {
        errSummary.SetError(txtEmail, "");
    }


}

9. Once we set the control and Error Message to the ErrorProvider control, an Alert icon is displayed to the user and the error message is displayed as a ToolTip.




10. The boolFormValid is a Form level bool variable, which is set to false, when any of the validations fail, while submitting the form, make sure that this is true, else alert the user to correct the validation errors.

        private void cmdSubmit_Click(object sender, EventArgs e)
        {
            boolFormValid = true;
            ValidateEmail();
            //
            if (!boolFormValid)
            {
                MessageBox.Show("Please correct the Validation Error.");
                return;
            }
       }



Search Flipkart Products:
Flipkart.com

2 comments:

Anonymous said...

Fantastic!!!! It worked perfectly for my project.

Anonymous said...

Muy bueno gracias