Validation checks incoming data against domain rules before it is used as a rich domain value. A Boolean says whether a check passed, but does not show downstream code that the check was performed. Instead, convert a raw value into a distinct validated type; functions that require that type can then accept only successfully converted values. section 9.2.1
Use Result when failure needs an explanation. Ok carries the validated value; Error carries a message describing what went wrong. An option can represent success or failure, but None cannot say why validation failed. section 9.2 section 9.2.1
Checking a customer
A raw customer may have an ID such as "C123" and a country supplied as a string. The validation function checks that the ID begins with "C", rejects an empty country, and converts "USA" to Domestic or another nonempty value to Foreign. It returns Ok with a Customer when the checks pass, or Error with a specific message when one fails. section 9.2.1
Listing 9.2 Using results instead of options for validation
let validateCustomer (rawCustomer:RawCustomer) =
let customerId =
if rawCustomer.CustomerId.StartsWith "C" then
Ok (CustomerId(int rawCustomer.CustomerId[1..])) #1
else
Error $"Invalid Customer Id '{rawCustomer.CustomerId}'." #2
let country =
match rawCustomer.Country with
| "" -> Error "No country supplied" #2
| "USA" -> Ok Domestic #1
| other -> Ok (Foreign other) #1
match customerId, country with
| Ok customerId, Ok country -> #3
Ok ... // body omitted for clarity
| Error err, _ #4
| _, Error err ->
Error err
The customer listing shows separate Result-producing checks and a final match that returns either a validated value or the first encountered error. section 9.2.1
For JSON input, keep deserialization and domain validation separate. Deserialize into a simple record that closely matches the JSON, then map that record into richer types with ordinary F# functions. This avoids putting domain rules inside custom JSON converters. section 10.2.1
For a web request, the same boundary can be handled in three steps:
- Map the raw JSON to a record of simple values. section 13.2.7
- Convert the record to a rich domain type, returning validation messages through Result.Error. section 13.2.7
- Map errors to an HTTP 4xx response; continue normal handling on success. section 13.2.7
Small, reusable functions are often enough. Validus supplies common checks such as string-length validation. A Result-based conversion here returns the first error; when all errors are needed, FsToolkit provides a Validation type. section 10.2.1 section 13.2.7






























