Validation in Gjallarhorn
Mutables in Gjallarhorn also provide a mechanism to filter based on validation rules.
The validation engine in Gjallarhorn can be used to validate any value. It is based on using function composition with built-in functions defining rules.
For example, we can validate a string:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: |
|
Note that our validation result, with "Foo" as input, was Valid - all of our rules were met.
However, when passing " a", we violated two of our input rules, and the resulting ValidationResult contains a list of all bad messages.
If you want to restrict the number of messages, you can use fixErrors (to stop collecting errors if we're already in an error state), or
fixErrorsWithMessage to stop collecting further errors as well as provide a custom error message.
This can be useful, for example, if validating a name as input. When the user hasn't entered anything (it's null or whitespace), we likely don't want to continue collecting errors, and instead want to report a custom error message:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: |
|
Again, using fixErrors or fixErrorsWithMessage stops collecting more errors, as demonstrated above. Even though an empty
string would fail the hasLengthAtLeast rule, that error is not added to the list of invalid reasons.
We can also do custom validation rules via the validateWith function. This accepts a function which takes the value, and returns a string option. When None,
the rule succeeds, when Some, the error is added to the invalid message list:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: |
|
Now that we've seen how to do basic validation, we'll extend this into Validating Signals
Full name: Validation.input
Full name: Validation.isValid
Full name: Validation.testInput
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Full name: Validation.badinput
Full name: Validation.testBad
Full name: Validation.validateName
Full name: Validation.isValidName
Full name: Validation.customRule
Full name: Validation.customValidation