Recipe 8.3 · C#
A Small Reusable Validator
Problem
DataAnnotations are good for field-level rules on simple types. They get awkward when rules depend on other services, apply only in some cases, or need to read like business sentences. Teams then fall back to a long Validate() method of nested if statements that returns the first error it finds, and every class does it differently.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
public string Validate(OrderRequest o)
{
string msg = "";
if (o.CustomerId == null || o.CustomerId.Trim() == "")
msg += "Customer is required<br/>";
if (o.Quantity < 1) msg += "Quantity must be positive<br/>";
if (o.Rush && o.ShipBy == null)
msg += "Ship-by date required for rush<br/>";
return msg;
}
The result is HTML in a string, so it cannot be shown in an API response or a log without stripping tags, and nothing ties a message to the field it belongs to. I have seen this exact shape in more Web Forms code-behind files than I can count.
The improved recipe
A base class of about sixty lines gives you a consistent shape: rules are declared in the constructor, every rule runs, and the result is a list of property/message pairs.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ImproveCode.Validation;
public sealed record ValidationError(string Property, string Message);
public sealed class ValidationOutcome
{
public ValidationOutcome(IReadOnlyList<ValidationError> errors)
{
Errors = errors;
}
public IReadOnlyList<ValidationError> Errors { get; }
public bool IsValid => Errors.Count == 0;
public IReadOnlyDictionary<string, string[]> ToDictionary() =>
Errors.GroupBy(e => e.Property)
.ToDictionary(
g => g.Key,
g => g.Select(e => e.Message).ToArray());
}
public abstract class Validator<T>
{
private readonly List<Func<T, ValidationError?>> _rules = [];
public ValidationOutcome Validate(T instance)
{
ArgumentNullException.ThrowIfNull(instance);
var errors = _rules
.Select(rule => rule(instance))
.OfType<ValidationError>()
.ToList();
return new ValidationOutcome(errors);
}
protected void Must<TProp>(
string property,
Func<T, TProp> selector,
Func<TProp, bool> isValid,
string message,
Func<T, bool>? when = null)
{
_rules.Add(x =>
(when is null || when(x)) && !isValid(selector(x))
? new ValidationError(property, message)
: null);
}
protected void NotEmpty(
string property, Func<T, string?> selector,
Func<T, bool>? when = null) =>
Must(property, selector,
v => !string.IsNullOrWhiteSpace(v),
$"{property} is required.", when);
protected void MaxLength(
string property, Func<T, string?> selector, int max) =>
Must(property, selector,
v => v is null || v.Length <= max,
$"{property} must be {max} characters or fewer.");
protected void Nested<TChild>(
string property,
Func<T, IEnumerable<TChild>?> selector,
Validator<TChild> childValidator)
{
ArgumentNullException.ThrowIfNull(childValidator);
_rules.Add(x =>
{
var first = (selector(x) ?? [])
.Select((child, i) => (i, childValidator
.Validate(child).Errors.FirstOrDefault()))
.FirstOrDefault(p => p.Item2 is not null);
return first.Item2 is null
? null
: new ValidationError(
$"{property}[{first.i}].{first.Item2.Property}",
first.Item2.Message);
});
}
}
public sealed record OrderLine(string Sku, int Quantity);
public sealed record OrderRequest(
string? CustomerId,
bool Rush,
DateOnly? ShipBy,
IReadOnlyList<OrderLine>? Lines);
public sealed class OrderLineValidator : Validator<OrderLine>
{
public OrderLineValidator()
{
NotEmpty(nameof(OrderLine.Sku), x => x.Sku);
MaxLength(nameof(OrderLine.Sku), x => x.Sku, 20);
Must(nameof(OrderLine.Quantity), x => x.Quantity,
q => q is >= 1 and <= 1000,
"Quantity must be between 1 and 1000.");
}
}
public sealed class OrderRequestValidator : Validator<OrderRequest>
{
public OrderRequestValidator()
{
NotEmpty(nameof(OrderRequest.CustomerId), x => x.CustomerId);
Must(nameof(OrderRequest.ShipBy), x => x.ShipBy,
d => d is not null,
"A ship-by date is required for rush orders.",
when: x => x.Rush);
Must(nameof(OrderRequest.Lines), x => x.Lines,
l => l is { Count: > 0 },
"At least one order line is required.");
Nested(nameof(OrderRequest.Lines), x => x.Lines,
new OrderLineValidator());
}
}
How it works
Each rule is a function from the object to either an error or null. Validate runs every rule, so the user sees all problems at once instead of fixing them one round trip at a time. Must is the general building block; NotEmpty and MaxLength are thin wrappers that keep the messages consistent across the application. The when parameter covers conditional rules like the rush-order date without an if in sight.
Nested validates child collections and reports the first failing child with an indexed path, Lines[2].Quantity, which a front end can map back to a grid row. Reporting only the first child error keeps a 5,000-line import from producing 5,000 messages; change it to SelectMany if you want them all.
ValidationOutcome.ToDictionary returns the same shape as Recipe 8.2, so DataAnnotations results and validator results can be merged and returned the same way. Validators have no state beyond their rule list, so register them as singletons.
Variations and pitfalls
- Use
nameof, not string literals. Property names in messages and keys then survive refactoring. - Async rules. "Customer exists" or "SKU is active" needs a database call. Don't make the whole validator async for one rule. Run cheap shape checks first with this class, and check existence in the application service, where the repository is already at hand.
- FluentValidation. If you need localization, rule sets, or async rules everywhere, FluentValidation (
FluentValidationon NuGet) is the mature version of this idea, and the rules translate almost line for line:RuleFor(x => x.Sku).NotEmpty().MaximumLength(20). I use the small class when a project needs a dozen validators and no new dependency. - Don't return HTML. Messages are plain text. The UI decides how to show them.