Today’s random F# code: validation

Today’s random F# code from our app is about validating data passed to us over our public API:

Example code showing the usage of FsToolkit.ErrorHandling’s validation computation expression.

A validation results either in Ok value or Error messages.

The validation computation expressions allow us to use let! and and! to combine small validations into bigger ones. let! executes a validation and if it fails, the whole computation expression blocks fails immediately (like a early return). With and!, we can execute several validations at once and combine the error messages if more than one sub-validation fails.

If we reach the return without any errors, we return the validated value.

I use the path value to build better error messages that let the caller quickly find errors in hierarchical data.

Validation of a complete data structure in our code.

Above, CreateActivity is the data we get from the API, ActivityOperationData.CreateActivity is the validated data. Regarding our public API, we always work with two models: one that reflects the JSON that can be passed to us directly, and a validated model that is used by our business logic.


This blog post is made possible with the support of Time Rocket, the product this blog post is about. Take a look (German only).

About the author

Urs Enzler

Add comment

By Urs Enzler

Recent Posts