liveBook · Manning

Validation

As explained in F# in Action: A Revised Edition of Get Programming with F#

Validation is the process of checking data against rules that determine whether it is acceptable for a domain or operation.

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

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Works through Result-based field checks and a raw-to-domain conversion, then outlines web response handling; it does not develop an all-errors implementation.
Examples
Uses customer IDs and countries, JSON guitar inventory, and raw web-request records to illustrate validation.
What it assumes
Introduces Result's success and error cases while relying on basic F# records, functions, and domain-type construction.
What you can do after
Build it from scratch with F# functions returning Result, or apply common checks via Validus.
How it connects
Connects validation to Result, option, discriminated unions, JSON deserialization, domain modeling, and HTTP 4xx responses.

Also explained in

Compare how 31 books explain validation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.