Validate a form's fields without trapping the user in a field in C#

The example Use the Validating event to make a form validate its fields 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), and set e.Cancel 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 user enters a valid value. If the user doesn't know a valid value yet, this prevents the user from filling in other fields first and 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 that event cancels the operation.

This example uses 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 event handlers. The following code shows how the OK button validates all of the fields.

// The user accepted the values.
private void btnOk_Click(object sender, EventArgs e)
{
// 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);
}

The code simply loops through each control on the form. For each control, the code uses the ErrorProvider'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 OK button's Click 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.

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.