Compose and chain validators using custom operators
mainValidus provides a set of custom operators in Validus.Operators to compose, chain, and transform validators. This allows you to build complex validation logic from simple building blocks.
Core Operators Reference
| Operator | Description |
|---|---|
<+> | Compose two validators of equal types |
*|* | Map the Ok result of a validator (high precedence, for use with choice <|> ) |
*| | Set the Ok result of a validator to a fixed value (high precedence, for use with choice <|> ) |
>>| | Map the Ok result of a validator (low precedence, for chained validation) |
>| | Set the Ok result of a validator to a fixed value (low precedence, for chained validation) |
>>= | Bind the Ok result of a validator with a function returning a Result |
<<= | Reverse-bind the Ok result of a validator with a function returning a Result |
>>% | Set the Ok result of a validator to a fixed Result value |
<|> | Choice: if the right-hand side validates Ok, pick that result; otherwise, continue with the next validator |
>=> | Kleisli-bind two validators (can change the result type) |
<=< | Reverse Kleisli-bind (right-hand side evaluated first; can change result type) |
.>> | Compose two validators, but keep the result of the left-hand side (ignores right-hand side unless it errors) |
>>. | Compose two validators, but keep the result of the right-hand side (ignores left-hand side unless it errors) |
.>>. | Compose two validators and keep the results of both sides as a tuple |
open Validus
open Validus.Operators
// Example: Chaining a pattern check, a conversion, and a range check
let ageValidator =
Check.String.pattern @"\d+" *|| Int32.Parse // Match pattern, then convert to Int32
>=> Check.Int.between 0 120 // Then check range