Title: Use the Validating event in C#
When focus moves from one control to another, the first can fire a Validating event. This only happens if the second control's CausesValidation property is true.
The program can set the Validating event handler's e.Cancel parameter to true to prevent focus from leaving the first 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 object'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;
}
}
All of the program's text boxes except the ZIP code text box 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 the RequiredFieldIsBlank method 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 text box 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 the RequiredFieldIsBlank method 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.)
So here's the sequence of events. When the user tries to move out of a TextBox, its Validating evnet fires. The event handler checks whether the TextBox contains valid text and, if it does not, sets e.Cancel = true to prevent focus from leaving the TextBox.
Note that the Validating event occurs no matter how the user tries to leave the TextBox. For example, if the user presses Tab, clicks on another control, presses Enter to trigger the Accept button, or presses Esc to trigger the Cancel button. The event triggers even if the user tries to close the form. That means the user cannot close the form unless the field passes validation.
Note also that the user can leave a field if it doesn't have a Validating event handler. For example, suppose you remove the event handler from the First Name TextBox. If you then start the program and immediately try to close it, The First Name TextBox doesn't prevent you from closing the form. None of the other TextBoxes gets the focus so their Validating event handlers never get a chance to run so the form closes.
Download the example to experiment with it and to see additional details.
|