Form Validation
Form validation is a critical part of any web application. It ensures that the data submitted by the user is accurate and secure. Fex provides a simple and flexible approach to form validation based on the built-in Result types in F#.
F# is an excellent choice when it comes to validating form data. It's a functional-first language that provides a powerful type system and a rich set of libraries for working with data. Below is an example using the Validus NuGet package.
app.post("/form-validation", fun req res next ->
let requestBody = req.body :?> RequestBody
let inputName = requestBody.inputName
let inputEmail = requestBody.inputEmail
let nameValidator fieldName =
let msg = fun _ -> $"{fieldName} must be between 3 and 64 characters"
Check.WithMessage.String.betweenLen 3 64 msg
let validatedInput =
validate {
let! inputName = nameValidator "Name" "inputName" inputName
and! inputEmail = nameValidator "Email address" "inputEmail" inputEmail
return {
inputName = inputName
inputEmail = inputEmail
}
}
let errors =
match validatedInput with
| Ok validInput -> Map.empty
| Error e -> e |> ValidationErrors.toMap
FormValidationPage ({| errors = errors; requestBody = requestBody |})
|> res.renderComponent
)
Again, since we're using the Fex architectural pattern we can turn off JavaScript in our web browsers and have the exact same experience.
Take a look in w3m, links, or lynx and you'll see that the form still works and the page still updates, allowing for the easy creation of a TUI web application!
Next: Request-Response Cycle Illustrated