Validate a form in C#

[validate]

The example Use the Validating event in C# explains how you can use a Validating event handler to check a field’s value when focus leaves that field. If the field’s value is invalid, the program can display a message, flag the error (perhaps with an ErrorProvider component), and set e.Cancel = true to prevent focus from leaving the field.

Unfortunately this method has a couple of drawbacks. First it traps the user in the field until the value is valid. If the user doesn’t know a valid value yet, this prevents the user from filling in other fields first and that can be frustrating.

Very experienced users also often type “heads down” without looking at the form. In that case the user may not notice the error until later and may continue entering more values in the invalid field.

Perhaps the biggest problem of all is that the user cannot cancel the form. Trying to close the form or clicking on the Close button moves focus out of the field that has the error, that raises the Validating event, and the event handler cancels the operation.

This example demonstrates a better solution. It uses Validating event handlers to flag invalid fields but it does not set e.Cancel to true so the user can still leave incorrect fields. Later, when the user clicks the OK button, the form checks the fields to see if any is invalid.

See the previous example for more information on using Validating events. The following code shows how the OK button validates all of the example’s fields.

// The user accepted the values.
private void btnOk_Click(object sender, EventArgs e)
{
    // Validate all fields.
    ValidateRequiredField(errField, txtFirstName);
    ValidateRequiredField(errField, txtLastName);
    ValidateRequiredField(errField, txtStreet);
    ValidateRequiredField(errField, txtCity);
    ValidateRequiredField(errField, txtState);
    ValidateZipCode(errField, txtZip);

    // See if any field has an error message.
    foreach (Control ctl in Controls)
    {
        if (errField.GetError(ctl) != "")
        {
            MessageBox.Show(errField.GetError(ctl));
            return;
        }
    }

    MessageBox.Show("You entered:\n" +
        txtFirstName.Text + ' ' + txtLastName.Text + '\n' +
        txtStreet.Name + '\n' +
        txtCity.Name + '\t' + txtState.Text + '\t' + txtZip.Text);
}

This code first calls validation methods to validate all of the TextBoxes.

It then loops through each control on the form. For each control, the code uses the ErrorProvider object’s GetError method to get the error associated with that control. If any control has a non-blank error message, the program displays it in a message box and exits the event handler.

If none of the controls has an error message, the program displays the values entered.

If the user clicks the Cancel button, the program simply closes the form without validating the fields. That lets you escape from the form if you decide you don’t want to fill it all out after all.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *