Trust is earned, not given

A different perspective

2025-01-18 · Projects

DotNetCode, part 3: CleanValidation — input parsing that never throws

Where does the NullReferenceException live? Usually one line after parsing user input. CleanValidation (part of DotNetCode) is a dependency-light library of null-tolerant text/number/date helpers that sit between raw input and your business logic, so the rest of the codebase never has to null-check or try/catch a parse.

The design decision: degrade instead of throw

using CV = CleanValidation.CleanValidation;

int quantity    = CV.Int32(request.Form["qty"]);      // "  42px " -> 42, "" -> 0
decimal price   = CV.Decimal(request.Form["price"]);  // "$1,234.567" -> 1234.57
bool isActive   = CV.Bit(request.Form["active"]);     // "true"/"1" -> true
DateTime placed = CV.Date(request.Form["date"]);      // null -> DateTime.MinValue

if (!CV.ValidateEmail(email)) return BadRequest("Invalid email.");

Int32("abc") returns 0. Date(null) returns DateTime.MinValue. Text(null) returns string.Empty. This is a deliberate trade-off — for input-cleaning code, "empty/zero" is a sensible default and the caller decides what to do with it; for business rules, use the Validate* methods and reject. The alternative design (throw on everything) pushes a try/catch into every call site, which is exactly the noise this library removes.

What the cleaning actually handles

Multi-targeting in practice

One project, net48;net6.0;net8.0;net10.0 (the multi-targeting idea), BCL-only plus System.Text.Json — which .NET 6+ ships in the box and net48 pulls as a package. That is the "intersection of dependencies" rule working in real life.

Repository: github.com/bobhuang1/DotNetCode/tree/master/CleanValidation