Validation in the presenter
Validation is the part of a form that most often ends up as a chain of if statements under a button, with a MessageBox for each one. Written that way it reports one problem at a time and cannot be tested. Written as a function that returns a list, it reports every problem at once, each one attached to a field, and the form only has to show the list.
The rules
A rule function takes the raw values, exactly as the controls hold them, and returns every error it finds. The field name is part of the error, so the view can put the message next to the right control:
internal readonly record struct FieldError(string Field, string Message);
internal static class RegistrationRules
{
public static List<FieldError> Validate(string name, string email, string ageText)
{
var errors = new List<FieldError>();
if (name.Trim().Length < 2)
{
errors.Add(new FieldError("name", "Enter at least two characters."));
}
if (!IsEmail(email))
{
errors.Add(new FieldError("email", "Enter an address like name@example.com."));
}
if (!int.TryParse(ageText, out var age))
{
errors.Add(new FieldError("age", "Enter a whole number."));
}
else if (age < 18 || age > 120)
{
errors.Add(new FieldError("age", "Enter an age between 18 and 120."));
}
return errors;
}
private static bool IsEmail(string value)
{
var at = value.IndexOf('@');
var dot = value.LastIndexOf('.');
return at > 0 && dot > at + 1 && dot < value.Length - 1 && !value.Contains(' ');
}
}
The function never stops at the first error, which is the difference the user feels: a form that says "enter a name" and then, after a second click, "enter an email" is a form that makes the user work. It also does not trim the email or reject a plus sign, because those are product decisions; it checks the two things every address needs, an @ and a dot after it, and leaves the rest to the server that will check it anyway.
int.TryParse is the parse that does not throw. The else if matters: when the text is not a number there is no age to compare, so the range check is skipped and the field gets one message, not two.
Errors per field
The view receives a list and maps each field name to a control. ErrorProvider draws a small icon next to the control and shows the message on hover, which is the least intrusive place for a validation message: the form does not move, nothing is modal, and the user sees all the problems at once. Lesson 021 covered the component; here it gets its purpose.
The view clears all three errors before setting the new ones. SetError(control, string.Empty) removes an icon, and a field whose error is gone must lose its icon, or the form accumulates yesterday's complaints.
The form and the presenter
The whole program. The presenter holds the save counter and the decision to report the count; the view holds the controls, the provider and the mapping from a field name to a control, built and not run:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new RegistrationForm());
}
}
internal interface IRegisterView
{
string Name { get; }
string Email { get; }
string AgeText { get; }
string Status { set; }
void ShowErrors(IReadOnlyList<FieldError> errors);
event EventHandler? SaveRequested;
}
internal readonly record struct FieldError(string Field, string Message);
internal static class RegistrationRules
{
public static List<FieldError> Validate(string name, string email, string ageText)
{
var errors = new List<FieldError>();
if (name.Trim().Length < 2)
{
errors.Add(new FieldError("name", "Enter at least two characters."));
}
if (!IsEmail(email))
{
errors.Add(new FieldError("email", "Enter an address like name@example.com."));
}
if (!int.TryParse(ageText, out var age))
{
errors.Add(new FieldError("age", "Enter a whole number."));
}
else if (age < 18 || age > 120)
{
errors.Add(new FieldError("age", "Enter an age between 18 and 120."));
}
return errors;
}
private static bool IsEmail(string value)
{
var at = value.IndexOf('@');
var dot = value.LastIndexOf('.');
return at > 0 && dot > at + 1 && dot < value.Length - 1 && !value.Contains(' ');
}
}
internal sealed class RegisterPresenter
{
private readonly IRegisterView _view;
private int _saved;
public RegisterPresenter(IRegisterView view)
{
_view = view;
view.SaveRequested += OnSave;
}
private void OnSave(object? sender, EventArgs e)
{
var errors = RegistrationRules.Validate(_view.Name, _view.Email, _view.AgeText);
_view.ShowErrors(errors);
if (errors.Count > 0)
{
_view.Status = $"{errors.Count} field(s) need attention.";
return;
}
_saved++;
_view.Status = $"Saved #{_saved}.";
}
}
internal sealed class RegistrationForm : Form, IRegisterView
{
private readonly TextBox _name = new() { Location = new Point(110, 18), Width = 220 };
private readonly TextBox _email = new() { Location = new Point(110, 50), Width = 220 };
private readonly TextBox _age = new() { Location = new Point(110, 82), Width = 80 };
private readonly Label _status = new() { Location = new Point(16, 150), AutoSize = true };
private readonly ErrorProvider _errors = new() { BlinkStyle = ErrorBlinkStyle.NeverBlink };
public RegistrationForm()
{
Text = "Registration";
ClientSize = new Size(360, 190);
var save = new Button { Text = "&Save", Location = new Point(110, 114), Size = new Size(100, 27) };
save.Click += (sender, e) => SaveRequested?.Invoke(this, EventArgs.Empty);
Controls.Add(new Label { Text = "&Name:", AutoSize = true, Location = new Point(16, 22) });
Controls.Add(new Label { Text = "&Email:", AutoSize = true, Location = new Point(16, 54) });
Controls.Add(new Label { Text = "&Age:", AutoSize = true, Location = new Point(16, 86) });
Controls.Add(_name);
Controls.Add(_email);
Controls.Add(_age);
Controls.Add(save);
Controls.Add(_status);
AcceptButton = save;
_presenter = new RegisterPresenter(this);
}
private readonly RegisterPresenter _presenter;
string IRegisterView.Name => _name.Text;
string IRegisterView.Email => _email.Text;
string IRegisterView.AgeText => _age.Text;
string IRegisterView.Status
{
set => _status.Text = value;
}
void IRegisterView.ShowErrors(IReadOnlyList<FieldError> errors)
{
_errors.SetError(_name, string.Empty);
_errors.SetError(_email, string.Empty);
_errors.SetError(_age, string.Empty);
foreach (var error in errors)
{
var control = error.Field switch
{
"name" => (Control)_name,
"email" => _email,
"age" => _age,
_ => _name,
};
_errors.SetError(control, error.Message);
}
}
public event EventHandler? SaveRequested;
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run. The switch expression returns a Control because the three concrete types share no nearer base that SetError accepts; the cast on the first arm sets the type of the whole expression and the other arms convert implicitly. The fallback arm exists so the expression is total, and it never runs for an error this presenter produces.
The presenter counts saves so a second successful click is visibly a second save. In a real form the count would be a call to a service, and the status line would say what the service answered.
A table of bad input
The rules alone, with no form, driven through six registrations. The program prints the number of errors and every message, and it was built and run here:
using System;
using System.Collections.Generic;
Console.WriteLine("six registration attempts");
var cases = new[]
{
("Ada", "ada@example.com", "36"),
("A", "ada@example.com", "36"),
("Ada", "ada.example.com", "36"),
("Ada", "ada@example.com", "x"),
("Ada", "ada@example.com", "12"),
("", "ada @example.com", ""),
};
foreach (var (name, email, age) in cases)
{
var errors = RegistrationRules.Validate(name, email, age);
Console.WriteLine($"name '{name}', email '{email}', age '{age}': {errors.Count} error(s)");
foreach (var error in errors)
{
Console.WriteLine($" {error.Field}: {error.Message}");
}
}
internal readonly record struct FieldError(string Field, string Message);
internal static class RegistrationRules
{
public static List<FieldError> Validate(string name, string email, string ageText)
{
var errors = new List<FieldError>();
if (name.Trim().Length < 2)
{
errors.Add(new FieldError("name", "Enter at least two characters."));
}
if (!IsEmail(email))
{
errors.Add(new FieldError("email", "Enter an address like name@example.com."));
}
if (!int.TryParse(ageText, out var age))
{
errors.Add(new FieldError("age", "Enter a whole number."));
}
else if (age < 18 || age > 120)
{
errors.Add(new FieldError("age", "Enter an age between 18 and 120."));
}
return errors;
}
private static bool IsEmail(string value)
{
var at = value.IndexOf('@');
var dot = value.LastIndexOf('.');
return at > 0 && dot > at + 1 && dot < value.Length - 1 && !value.Contains(' ');
}
}
dotnet run
six registration attempts
name 'Ada', email 'ada@example.com', age '36': 0 error(s)
name 'A', email 'ada@example.com', age '36': 1 error(s)
name: Enter at least two characters.
name 'Ada', email 'ada.example.com', age '36': 1 error(s)
email: Enter an address like name@example.com.
name 'Ada', email 'ada@example.com', age 'x': 1 error(s)
age: Enter a whole number.
name 'Ada', email 'ada@example.com', age '12': 1 error(s)
age: Enter an age between 18 and 120.
name '', email 'ada @example.com', age '': 3 error(s)
name: Enter at least two characters.
email: Enter an address like name@example.com.
age: Enter a whole number.
The output is the real run. The last line is the one the design exists for: three problems reported at once, each with the field it belongs to, so the form can put three icons up and the user fixes everything in one pass. The whitespace in the address made the email rule fail as well, and the empty age produced the parse message rather than the range message.
Exercises
- Add a password field with a rule of eight characters and a digit, and a fourth error to the table.
- Change Validate to stop at the first error and compare the output of the last case with the table above.
- Replace the field names with an enum and explain what the view mapping gains and loses.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the rule function return?
Answer
Every error it finds, each with a field name and a message
The list is what lets the form show all the problems at once.
-
Why does the view clear all three errors before setting new ones?
Answer
A field whose error is gone must lose its icon
Otherwise yesterday's errors stay next to the controls.
-
Which parse does the age rule use?
Answer
int.TryParse, which does not throw
A failed parse is an ordinary branch, not an exception.
-
Why is the range check an else if after the parse?
Answer
There is no age to compare when the text is not a number
One field gets one message, not two.
-
What does ErrorProvider.SetError(control, string.Empty) do?
Answer
Removes the icon from that control
An empty message is how one field is cleared.
-
What did the run print for the last case?
Answer
3 error(s), one for each field
The empty name, the space in the address and the empty age each failed.
-
Why does the switch expression cast its first arm to Control?
Answer
The three control types share no nearer base that SetError accepts
The cast gives the expression its type; the other arms convert implicitly.
-
Where does the save counter live?
Answer
In the presenter, not in the view
It is a decision of the screen, so it is presenter state.
-
What does the presenter do when the list is empty?
Answer
Counts the save and writes the status line
The successful path is the presenter's, as in the login form.
-
What does the email rule check?
Answer
An @ with a dot after it, and no space
The server checks the rest; the form checks what a typo breaks.
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