Validating and Validated
A TextBox reports every keystroke with TextChanged, which is too often for a message and too rarely for a decision: the moment a field should be checked is the moment the user leaves it. WinForms has two events for that moment, Validating and Validated, and a way to keep the focus in the field when the check fails.
Validating and Validated
The order when the focus leaves a control is: Leave, Validating, Validated, the new control's Enter. The validation pair runs between the two controls, which is why a handler can refuse the move.
using System;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
internal sealed class Form1 : Form
{
private readonly TextBox _code = new() { Location = new Point(90, 16), Width = 160 };
private readonly NumericUpDown _amount = new() { Location = new Point(90, 52), Width = 120, DecimalPlaces = 2 };
private readonly ErrorProvider _errors = new() { BlinkStyle = ErrorBlinkStyle.NeverBlink };
private readonly Label _status = new() { Location = new Point(16, 96), AutoSize = true };
public Form1()
{
Text = "Validated fields";
ClientSize = new Size(360, 140);
var codeLabel = new Label { Text = "&Code:", Location = new Point(16, 20), AutoSize = true };
var amountLabel = new Label { Text = "&Amount:", Location = new Point(16, 56), AutoSize = true };
var save = new Button { Text = "&Save", Location = new Point(16, 120) };
_code.Validating += OnCodeValidating;
_code.Validated += (sender, e) => _status.Text = "code accepted";
_amount.Validating += OnAmountValidating;
save.Click += (sender, e) =>
{
if (ValidateChildren())
{
_status.Text = "ready to save";
}
};
Controls.Add(codeLabel);
Controls.Add(amountLabel);
Controls.Add(_code);
Controls.Add(_amount);
Controls.Add(save);
Controls.Add(_status);
}
private void OnCodeValidating(object? sender, System.ComponentModel.CancelEventArgs e)
{
if (_code.Text.Trim().Length != 0)
{
_errors.SetError(_code, string.Empty);
return;
}
_errors.SetError(_code, "A code is required");
e.Cancel = true;
}
private void OnAmountValidating(object? sender, System.ComponentModel.CancelEventArgs e)
{
if (_amount.Value > 0m)
{
_errors.SetError(_amount, string.Empty);
return;
}
_errors.SetError(_amount, "The amount must be greater than zero");
e.Cancel = true;
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. e.Cancel = true keeps the focus where it is, so the user cannot leave an empty code field by tabbing away; the error icon from the lesson before says why. Validated fires only when the check passed, which is why the status line is the right place for it.
Cancelling the leave
A cancelled Validating has two consequences worth knowing, and both surprise a reader once:
- The user cannot leave the field by mouse or by Tab. Escape and the window's close button still work, because those are not focus changes a form can refuse — which means a field that must be filled cannot trap the user in the application.
- A button whose CausesValidation is false can be pressed while a field is invalid. That is the property that lets a Cancel button work; the default is true.
- A form whose AutoValidate is EnablePreventFocusChange (the default) behaves as above. EnableAllowFocusChange lets the focus move and keeps the error, which is the calmer choice for a form that validates many fields.
The order also means that Validating does not run when the form closes. A Save button that calls ValidateChildren() is the only way to be sure that every field was checked at the moment of saving, because ValidateChildren raises the event on every child that can be validated, whatever the focus is doing.
The whole form
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
internal sealed class Form1 : Form
{
private readonly TextBox _name = new() { Location = new Point(90, 16), Width = 200 };
private readonly TextBox _email = new() { Location = new Point(90, 52), Width = 200 };
public Form1()
{
Text = "Two fields";
ClientSize = new Size(340, 130);
AutoValidate = AutoValidate.EnableAllowFocusChange;
_name.Validating += (sender, e) => e.Cancel = _name.Text.Trim().Length == 0;
_email.Validating += (sender, e) => e.Cancel = !_email.Text.Contains('@');
Controls.Add(new Label { Text = "&Name:", Location = new Point(16, 20), AutoSize = true });
Controls.Add(new Label { Text = "&Email:", Location = new Point(16, 56), AutoSize = true });
Controls.Add(_name);
Controls.Add(_email);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (!ValidateChildren())
{
e.Cancel = true;
}
base.OnFormClosing(e);
}
}
That block is a fragment: a form with no Main, so the checker counts it and does not build it. The override is the other half of the rule: closing the window is not a focus change, so the form asks ValidateChildren itself and cancels the close when a field is wrong. Without the override the window closes and the invalid data is never seen.
The rules that run
The check itself is a method over values, and every rule of the form can be tested without a control. This program validates three fields and prints what is wrong, and it runs here:
using System;
using System.Collections.Generic;
using System.Globalization;
var form = new FormModel();
form.Set("name", " ");
form.Set("price", "-5");
form.Set("date", "2026-11-30");
var errors = form.Validate();
foreach (var error in errors)
{
Console.WriteLine($"{error.Field,-6} {error.Message}");
}
Console.WriteLine($"errors: {errors.Count}");
Console.WriteLine($"valid: {form.Validate().Count == 0}");
internal sealed record Error(string Field, string Message);
internal sealed class FormModel
{
private readonly Dictionary<string, string> _values = new();
public void Set(string field, string value) => _values[field] = value;
public string Get(string field) => _values.TryGetValue(field, out var value) ? value : string.Empty;
public List<Error> Validate()
{
var errors = new List<Error>();
if (Get("name").Trim().Length == 0)
{
errors.Add(new Error("name", "A name is required"));
}
if (!decimal.TryParse(Get("price"), NumberStyles.Number, CultureInfo.InvariantCulture, out var price))
{
errors.Add(new Error("price", "A price must be a number"));
}
else if (price <= 0m)
{
errors.Add(new Error("price", "A price must be greater than zero"));
}
if (!DateTime.TryParse(Get("date"), CultureInfo.InvariantCulture, DateTimeStyles.None, out _))
{
errors.Add(new Error("date", "The date is not a date"));
}
return errors;
}
}
dotnet run
name A name is required
price A price must be greater than zero
errors: 2
valid: False
The output is the real run. The name is a space, which is why the rule trims before it decides; the price parses as a number and still fails the second rule, which is the case a single TryParse would miss; the date is valid and produces no line. The list is what a form maps onto ErrorProvider.SetError one field at a time, and the count is what a Save button tests before it writes anything. A rule that returns a List<Error> instead of a bool is the shape the rest of the course uses, because the second rule of a field needs a message of its own.
Exercises
- Add a fourth field whose rule needs two values, such as a date that must come after another, and run the program.
- Make the price rule accept zero and run it again. Which lines disappear?
- Explain from the documentation what ValidateChildren does with a control whose CausesValidation is false.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
In what order do the events run when the focus leaves a field?
Answer
Leave, Validating, Validated, then Enter on the new control
The validation pair sits between the two controls, which is why it can refuse the move.
-
What does e.Cancel = true in a Validating handler do?
Answer
Keeps the focus in the field
The leave is refused, and the new control never gets Enter.
-
When does Validated fire?
Answer
Only when the check passed
A cancelled Validating skips Validated.
-
Which property lets a Cancel button work while a field is invalid?
Answer
CausesValidation = false on the button
The button then does not raise the validation of the fields.
-
What does ValidateChildren() do?
Answer
Raises Validating on every child that can be validated and reports whether all passed
It is the whole-form check behind a Save button.
-
Why does closing the form not raise Validating?
Answer
A close is not a focus change
The form calls ValidateChildren itself, in OnFormClosing, if it wants the check.
-
What does AutoValidate.EnableAllowFocusChange change?
Answer
The focus may leave an invalid field, and the error stays
It is the calmer mode for a form with many fields.
-
What did the run print for the price field?
Answer
A price must be greater than zero
-5 parses as a number and fails the second rule.
-
Why does the name rule trim the text before deciding?
Answer
A field of spaces is empty as far as the user is concerned
The run's first line comes from a value of one space.
-
Which class does a validating handler's argument have?
Answer
CancelEventArgs
It carries the Cancel flag and nothing else.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.
Article author: Arthur Isaev