Chapter 8
Validation You Can Trust
Every system I have been asked to stabilize had a validation story, and in most of them the story was "a bit everywhere." Some checks lived in JavaScript on the page. Some lived in a Validate() method that half the screens called. Some lived in stored procedures as RAISERROR calls. And some lived nowhere, which is how a negative quantity ended up on a shipping manifest at a distribution client and nobody noticed until the truck was loaded.
Validation code is also one of the most commonly rewritten pieces of plumbing. Across the archive behind this book, 28 of the engagements had their own validation classes, 6,371 of them in total. Most were variations on the same few ideas: a ValidationHelper full of IsNumeric and IsValidEmail methods, a base class that collected error strings, and a regular expression copied from a forum post in 2006. None of that is wrong in spirit. It is just repeated, inconsistent, and hard to test.
This chapter gives you a small, layered approach. Guard clauses stop bad arguments at the method boundary. DataAnnotations and a tiny validator handle user input. Uploaded files get their own checks, because a file name and a byte stream are not the same thing as a form field. And the last recipe draws the line between validating at the edge of the system and protecting the rules inside the domain, so you know which check belongs where.
The recipes use only the base class library. If your team already uses FluentValidation, the ideas carry over directly; I point out where.
Recipes
- 8.1Guard Clauses with the Built-in Throw HelpersPublic methods receive arguments they cannot work with: a null dependency, an empty customer ID, a negative amount. Without a check, the method fails…
- 8.2DataAnnotations That Actually RunYou decorate a request class with [Required] and [StringLength], and in ASP.NET Core MVC the framework checks them for you. Then the same class is…
- 8.3A Small Reusable ValidatorDataAnnotations are good for field-level rules on simple types. They get awkward when rules depend on other services, apply only in some cases, or…
- 8.4Validating Uploaded FilesA user uploads a file, and the code checks that the name ends in .pdf. That check says nothing about the content. A renamed executable passes, and so…
- 8.5Validating at the Boundary and Inside the DomainOnce a team adopts validators, the next question is where to put them. One camp validates only in the controller, and the domain objects accept…
Chapter checklist
- Replace hand-written
if (x == null) throwblocks withArgumentNullException.ThrowIfNull,ArgumentException.ThrowIfNullOrWhiteSpaceand the .NET 8ArgumentOutOfRangeExceptionhelpers. - Search the code base for
TryValidateObject(and make sure every call passesvalidateAllProperties: true. - Return validation errors as property/message pairs, never as HTML strings, and show the user all of them at once.
- Put cross-field and conditional rules in one validator per request type, with
nameoffor property names. - For uploads, allow-list extensions, enforce a size limit, check the leading bytes and store files under a server-generated name outside the web root.
- Validate shape at the boundary; make domain objects protect their own invariants with private setters and guarded methods.
- Define each limit once, in the domain, and have the boundary read it.
- Keep
NOT NULL,CHECKand unique constraints in the database as the final safety net.