Use the Validating event to make a form validate its fields in C#

When focus moves from one control to another, the first can fire a Validating event handler. This only happens if the second control's CausesValidation property is true.

The program can set the event handler's e.Cancel parameter to true to prevent focus from leaving the control. In that case you should also somehow tell the user that there's a problem with the field. For example, you could display an error message, change the field's background color, or at least beep to let the user know that focus did not leave the field because something is wrong.

This example uses a couple of helper methods. The CamelCaseToWords method shown in the following code converts a string in camel case format likeThisOne into a series of space separated words, removing the first part to give "This One."

// Split a string in camelCase, removing the prefix.
private string CamelCaseToWords(string input)
{
// Insert a space in front of each capital letter.
string result = "";
foreach (char ch in input.ToCharArray())
{
if (char.IsUpper(ch)) result += " ";
result += ch;
}

// Find the first space and remove everything before it.
return result.Substring(result.IndexOf(" ") + 1);
}

The RequiredFieldIsBlank method shown in the following code determines whether a required field is blank. If it is blank, the method sets an error on the field using an ErrorProvider. Otherwise it clears the ErrorProvider's error message.
// Validate a required field. Return true if the field is valid.
private bool RequiredFieldIsBlank(ErrorProvider err, TextBox txt)
{
if (txt.Text.Length > 0)
{
// Clear the error.
err.SetError(txt, "");
return false;
}
else
{
// Set the error.
err.SetError(txt, CamelCaseToWords(txt.Name) + " must not be blank.");
return true;
}
}

Each of the program's TextBoxes except the one for the ZIP code share the following Validating event handler.

// Validate fields.
private void txtRequiredField_Validating(object sender, CancelEventArgs e)
{
TextBox txt = sender as TextBox;
e.Cancel = RequiredFieldIsBlank(errField, txt);
}

This code calls RequiredFieldIsBlank to set or clear the TextBox's error message. It sets e.Cancel to the result returned by that method so the focus cannot leave the TextBox if there is an error.

Finally the ZIP code TextBox uses the following Validating event handler. It's a bit more complicated because it checks the field's format.
// Validate the ZIP code.
private void txtZip_Validating(object sender, CancelEventArgs e)
{
// Check for missing value.
if (RequiredFieldIsBlank(errField, txtZip))
{
e.Cancel = true;
return;
}

// Check for correct format.
Regex regex = new Regex(@"^(\d{5}|\d{5}-\d{4})$");
if (regex.IsMatch(txtZip.Text))
{
// Clear the error.
errField.SetError(txtZip, "");
}
else
{
// Set the error.
errField.SetError(txtZip, "ZIP code must have format ##### or #####-####.");
e.Cancel = true;
}
}

This code calls RequiredFieldIsBlank to make sure the user entered a value. It then uses a regular expression to make sure the entered text has the format ##### or #####-####. (You can change this to fit your postal code system if you're not in the U.S.)

  

 

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.